0

I'm making a game in Java with Swing. I created a start menu. I want the game to start when I press the start button.

I have a start button in my startScreen object. I want to add game object to my frame when I press.

I try very bad way:

while(startScreen.isVisible()){
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(Core.class.getName()).log(Level.SEVERE, null, ex);
        }
    }window.add(gameScreen);

What is the true way?

zer0
  • 1
  • 3
  • i dont see the usage of any button anywhere. Why do you use sleep? – f1sh Mar 11 '20 at 18:44
  • 1
    Instead of making the program wait, why not start the function when the button is pressed? – MT756 Mar 11 '20 at 18:45
  • Without knowing much regarding your code structuring, you want to make sure your program's main loop is in a method that gets called when you select the start button. Any specific details would require further information on your part about your program's structuring and classes. – Tim Hunter Mar 11 '20 at 18:49
  • See https://stackoverflow.com/questions/284899/how-do-you-add-an-actionlistener-onto-a-jbutton-in-java – admlz635 Mar 11 '20 at 18:50

1 Answers1

0

Depending on what type of 'button' you're referring to, your implementation may change. But, for example, using a JButton, you could register some action to do when the button is pressed. Something like:

button.addActionListener(event -> {
    // Do whatever it is that you're wanting to do in here...
    System.out.println("The button was pressed...");
});
BeUndead
  • 3,463
  • 2
  • 17
  • 21