Java – buttons in java, creating and using action listeners

appleteclipsejavaradio-buttonswing

im really new to eclipse and I am creating buttons for the first time. I think I have the basic idea but its not working. Anything that you can add on any part of my code is really helpful. Help! here is my code:

import java.applet.Applet; 
import java.awt.*; 
import java.awt.event.*; 

public class MovingBox extends Applet 
{
  Thread thread; 
  Dimension dim; 
  Image img; 
  Graphics g; 
  Color red = null;
  Color blue = null;
  Font fnt16P = null;


  public void init()
  { 
    resize(800,500);    


    Button b_Up = new Button("Up"); 
    b_Up.setSize(100, 25);
    b_Up.setLocation(450,450+ 90);
    b_Up.setBackground(red); 
    b_Up.setForeground(blue);
    b_Up.setFont(fnt16P);
    b_Up.setVisible(true);
    b_Up.addActionListener((ActionListener) this);
    add(b_Up);


  }

  public void paint(Graphics gfx)
  {
    g.setColor(Color.green);
    g.fillRect(0,0,800,500);
  }
  public void actionPerformed(ActionEvent event)
  {
    int value, total;;
    Object cause = event.getSource();

    if (cause == b_Up)
    (
    )

  }

}

Best Solution

Don't define Graphics objects. Use the Graphics object that is passed to the method.

Graphics g; 
...
public void paint(Graphics gfx)
  {
    g.setColor(Color.green);
    g.fillRect(0,0,800,500);
  }

Don't set the size/location manually. Use a layout manager and let the layout manager do its job.

Button b_Up = new Button("Up"); 
b_Up.setSize(100, 25);
b_Up.setLocation(450,450+ 90);

I suggest you spend time learning how to use Swing instead of learning AWT. Start with the Swing tutorial for the basics.