我正在編寫一個非常基本的代碼,使點在屏幕上移動。我的目標是最終有一個冒險遊戲。它主要是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();
}
}
當我在電腦上運行它時,左右按鈕可以工作,但上下按鈕不起作用。這是怎麼回事?
請縮進代碼,以便它是可讀 – njzk2 2014-10-10 17:48:09
動作監聽器沒有設置在downlistener – njzk2 2014-10-10 17:50:37
如果你使用'X ++',爲什麼你不使用'X - '(而不是'x = x - 1')? – Tom 2014-10-10 17:50:51