java applet,按钮运行时问题数组

时间:2014-05-08 10:25:43

标签: java applet

我正在构建一个带有java杯图像的applet,可以通过单击5个按钮将其重新定位,以便在applet窗口的主区域中移动它。代码似乎编译但我在尝试运行时遇到错误。虽然我错了,但我确定我没有正确使用阵列。是的,我知道AWT已经老了,但我必须为我的课程学习...任何帮助都会非常感谢大家!

 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

1 个答案:

答案 0 :(得分:1)

像这样初始化Keyarray:

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

另外,初始化Panel

private Panel Keypad = new Panel();