I want to call the "main thread" (the initial thread that starts main()) to do some work using the actionPerformed()ActionListener button method, but I don't know how to do this.
A bit more context:
I am currently programming a 2D game using Swing (Tetris flavor).
When the application starts, a window opens in which the main menu of the game is displayed. The user is offered several options, one of which is to start the game by pressing the "Start" button, which causes the display of the game panel and starts the main game cycle.
To be able to switch between two panels (in the main menu and in the game), I use the CardLayout manager, then I can display one panel by calling show().
The idea is that I would like my start button to have a listener that looks like this:
public class StartListener implements ActionListener {
StartListener() {}
public void actionPerformed(ActionEvent e) {
displayGamePanel();
startGame();
}
}
but this does not work, because it is called from the event-event stream actionPerformed(), so the call startGame()(which starts the main loop: updating logical logic + repaint()on each frame) blocks the entire thread.
The way I'm handling this right now is that it actionPerformed()simply changes the value of the boolean flag: public void actionPerformed(ActionEvent e) {
startPushed = true;
}
which is then eventually checked by the main thread:
while (true) {
while (!g.startPushed) {
try {
Thread.sleep(100);
} catch (Exception e) {}
}
g.startPushed = false;
g.startGame();
}
But I think this decision is very inelegant.
Concurrency Swing, ( Worker Thread - , overkill?). , .
( , ) ", ( )"?
.
EDIT:
, :
long lastLoopTime = System.currentTimeMillis();
long dTime;
int delay = 10;
while (running) {
dTime = System.currentTimeMillis() - lastLoopTime;
lastLoopTime = System.currentTimeMillis();
updateState(dTime);
frame.repaint()
try {
Thread.sleep(delay);
} catch (Exception e) {}
}