im building a applet with a image of a java cup that can be repositioned by the clicking of 5 buttons to move it in the main area of the applet window. the code seems to compile but I get errors when trying to run it. I'm sure I'm not using the array correctly although I could be wrong. And yes guys I know AWT is old but i have to learn it for my course...any help would be great thanks guys!

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


 public class moveIt extends Applet implements ActionListener {

    private Image cup;
    private Panel Keypad;
    public int top = 15;
    public int left = 15;
    private Button Keyarray[];

    public void init () {
            cup=getImage(getDocumentBase(), "cup.gif");
            Canvas myCanvas= new Canvas();

            Keyarray[0] = new Button ("Up");
            Keyarray[1] = new Button ("Left");
            Keyarray[2] = new Button ("Down");
            Keyarray[3] = new Button ("Right");
            Keyarray[4] = new Button ("Center");
            setBackground(Color.BLUE);

            Panel frame = new Panel();
            frame.setLayout(new BorderLayout());
            frame.add(myCanvas, BorderLayout.NORTH);
            frame.add(Keypad, BorderLayout.SOUTH);

            Keypad.setLayout(new BorderLayout());


            Keypad.add(Keyarray[0], BorderLayout.NORTH);
            Keypad.add(Keyarray[1], BorderLayout.WEST);
            Keypad.add(Keyarray[2], BorderLayout.SOUTH);
            Keypad.add(Keyarray[3], BorderLayout.EAST);
            Keypad.add(Keyarray[4], BorderLayout.CENTER);

            Keyarray[0].addActionListener(this);
            Keyarray[1].addActionListener(this);
            Keyarray[2].addActionListener(this);
            Keyarray[3].addActionListener(this);
            Keyarray[4].addActionListener(this);


}//end of method init


public void paint(Graphics g) {
        g.drawImage(cup, left, top, this);
}

public void actionPerformed(ActionEvent e) {
        String arg = e.getActionCommand();

        if (arg == "Up")
            top -= 15;
        if (arg == "Down")
            top += 15;
        if (arg == "Left")
            left -= 15;
        if (arg == "Right")
            left += 15;
        if (arg == "Center") {
            top=60;
            left=125;
        }

        repaint();

    }//end paint method

}//end of class
有帮助吗?

解决方案

Initialize Keyarray like this:

private Button Keyarray[] = new Button[5];

Also, initialize Panel

private Panel Keypad = new Panel();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top