Start game from action listener

I have a blackjack game that I made in Java and I want to tell the start of the game by clicking a button. All my work listeners work very well and all that, but the problem is that I can’t understand how to start the game without starting it completely in the actionPerformed method. Obviously, a function that constantly works in the actionPerformed method will effectively disable the rest of my GUI. Here is the code snippet ....

go.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // START GAME SOMEHOW but must run outside of action listener } }); 
+6
source share
3 answers

Obviously, a function that is constantly executed in the actionPerformed method will effectively disable the rest of my GUI.

This is a good observation and shows that you understand the basic rule when working with Swing.

Your game is most likely event driven (correct me if I am wrong), so the action performed by the button should simply set the program to a new state, waiting for further events. This should not take much time, and usually this is done directly by the EDT.

Of course, if you want to make a fancy animation of the beginning of a new game, which should be performed in a separate thread, in this case you just start the animation stream (I would recommend using SwingWorker, though) from inside the actionPerformed method, and then return.

In the code, I think it would look something like this:

 go.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Remove the menu components someJPanel.removeAll(); // Show the game table someJPanel.add(new GamePanel()); someJPanel.revalidate(); someJPanel.repaint(); // done. Wait for further user actions. } }); 
+7
source

You should probably start the game in your thread and handle it yourself (it's hard to say), but to get started, you can start the game in a new "external" thread, something like this in your actionPerformed:

 public void actionPerformed(ActionEvent e) { Thread thread = new Thread("Game thread") { public void run() { startGame(); //or however you start your game } }; thread.start(); } 
+1
source

I believe you want to extend javax.swing.SwingWorker .

The non-ui start function will work in doInBackground and done will be called when it finishes updating ui.

There is even an example in the javadoc class description for updating the progress panel with the status of what happens at startup.

+1
source

Source: https://habr.com/ru/post/915535/


All Articles