I want to be able to press a button and a small game using Java 2d is created. i have tried to use a try/catch but it gets stuck in an infinite loop (because of the while loop in the create method i guess)
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.***/
}
});
here is the code from the create method:
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);
}
}
I believe that your infinite loop is blocking the swing thread from responding to your button.
Try having your loop in a separate thread:
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();
}