gpt4 book ai didi

java小程序,按钮数组运行时问题

转载 作者:行者123 更新时间:2023-12-01 13:00:39 24 4
gpt4 key购买 nike

我正在构建一个带有 java 杯子图像的小程序,可以通过单击 5 个按钮将其移动到小程序窗口的主区域中来重新定位。该代码似乎可以编译,但在尝试运行它时出现错误。我确信我没有正确使用数组,尽管我可能是错的。是的,我知道 AWT 很旧,但我必须为我的类(class)学习它......任何帮助都会非常感谢你们!

 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

最佳答案

像这样初始化Keyarray:

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

另外,初始化面板

private Panel Keypad = new Panel();

关于java小程序,按钮数组运行时问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23539110/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com