<分区>
我正在编写一个非常基本的代码来让一个点在屏幕上四处移动。我的目标是最终制作一款冒险游戏。它主要是 GUI,但我的按钮有一些问题。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class gui {
int x = 240;
int y = 240;
JPanel panel1 = new JPanel();
MyDrawPanel drawpanel = new MyDrawPanel();
public void go() {
JFrame frame = new JFrame("DotMover");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.CENTER, drawpanel);
frame.getContentPane().add(BorderLayout.SOUTH, panel1);
frame.setSize(500, 500);
drawpanel.repaint();
JButton leftbutton = new JButton("<----");
leftbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
x = x - 1;
drawpanel.repaint();
}
});
panel1.add(leftbutton);
JButton rightbutton = new JButton("---->");
rightbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
x++;
drawpanel.repaint();
}
});
panel1.add(rightbutton);
JButton upbutton = new JButton("Up");
upbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
y++;
drawpanel.repaint();
}
});
panel1.add(upbutton);
JButton downbutton = new JButton("Down");
upbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
y = y - 1;
drawpanel.repaint();
}
});
panel1.add(downbutton);
frame.setVisible(true);
}
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.GREEN);
g.fillOval(x, y, 20, 20);
}
}
}
public class dotmoveriii {
public static void main(String[] args) {
gui a = new gui();
a.go();
}
}
当我在我的计算机上运行它时,左右按钮可以工作,但向上和向下按钮不起作用。这是怎么回事?