我如何在 JButton ActionListener 中调用需要 InterruptedException 的方法
How do i call a method that requires an InterrupedException in a JButton ActionListner
我希望能够按下一个按钮并创建一个使用 Java 2d 的小游戏。
我曾尝试使用 try/catch 但它陷入了无限循环(我猜是因为创建方法中的 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.***/
}
});
这是创建方法的代码:
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);
}
}
我认为您的无限循环正在阻止摆动线程响应您的按钮。
尝试将循环放在单独的线程中:
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();
}
我希望能够按下一个按钮并创建一个使用 Java 2d 的小游戏。 我曾尝试使用 try/catch 但它陷入了无限循环(我猜是因为创建方法中的 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.***/
}
});
这是创建方法的代码:
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);
}
}
我认为您的无限循环正在阻止摆动线程响应您的按钮。
尝试将循环放在单独的线程中:
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();
}