我希望能够按下按钮,并创建使用Java 2d的小游戏。 我试图使用try / catch但是它被卡在无限循环中(因为我想在create方法中使用while循环)
Button.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
game.create();/***is a new window with a small 2d game,
the 'create' method requires and InterruptedException to be thrown.***/
}
});
这是create方法的代码:
public void create () throws InterruptedException {
JFrame frame = new JFrame("Mini Tennis");
GameMain gamemain = new GameMain();
frame.add(gamemain);
frame.setSize(350, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
gamemain.move();
gamemain.repaint();
Thread.sleep(10);
}
}
答案 0 :(得分:2)
我相信你的无限循环会阻止摇摆线程响应你的按钮。
尝试将循环放在一个单独的线程中:
public void create () throws InterruptedException {
JFrame frame = new JFrame("Mini Tennis");
GameMain gamemain = new GameMain();
frame.add(gamemain);
frame.setSize(350, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
(new Thread() {
public void run() {
while (true) {
gamemain.move();
gamemain.repaint();
Thread.sleep(10);
}
}
).start();
}