我只研究了直到方法,没有足够的耐心等到我的 UNI 教我剩下的东西,所以我发现这很有趣......我想创建一个中间有一个圆圈的 GUI,它会根据你用 java 按下的按钮移动。经过大量阅读后,我设法以这种方式完成了它。因此,在我遇到问题中提到的错误之前,我有 19 个错误,只有当我弄清楚所有错误时,这个错误才突然出现。我希望我不会激怒任何人,因为我确信这个错误是由于缺乏编程基础造成的。任何帮助将不胜感激。我指出错误发生在“<---”
import java.awt.*;
import java.awt.event.*;
public class Move_the_ball extends Frame {
public static void main(String[] args) {
Move_the_ball me = new Move_the_ball();
me.setVisible(true);
}
public Move_the_ball(){
setSize(700,700);
setLocation(100,100);
setTitle("Moving the ball");
setLayout(new BorderLayout());
Panel buttonPanel = new Panel();
buttonPanel.setBackground(Color.blue);
buttonPanel.setLayout(new FlowLayout());
Button goUp = new Button("Go up");
goUp.addActionListener(this); <-----------------
buttonPanel.add(goUp);
Button goDown = new Button("Go down");
goDown.addActionListener(this); <--------------
buttonPanel.add(goDown);
Button turnRight = new Button("Turn right");
turnRight.addActionListener(this); <-------------
buttonPanel.add(turnRight);
Button turnLeft = new Button("Turn left");
turnLeft.addActionListener(this); <---------------
buttonPanel.add(turnLeft);
}
public void paint(Graphics g)
{
g.fillOval(x,y,h,d);
}
private int x=200;
private int y=100;
private int h=50;
private int d=50;
public void actionPerformed (ActionEvent e){
String actionCommand = e.getActionCommand();
if(actionCommand.equals("Go up"))
{
y=y-5;
repaint();
} else if (actionCommand.equals("Go down"))
{
y=y+5;
repaint();
} else if (actionCommand.equals("Turn right"))
{
x=x+5;
repaint();
} else if (actionCommand.equals("Turn left"));
{
x=x-5;
repaint();
}
}
}