I try to create a game. Game logic and painting work fine if I start the game directly. But there is empty JPanel after I start a game from a menu. Why?
Start game directly:
There is a "infinitive" loop called gameLoop()
which stops after a game ends.
public class Window extends JFrame {
public Window() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setTitle("Shop-Lifter");
setFocusable(true);
setVisible(true);
}
public static void main(String[] args) {
Window window = new Window();
GameCore gameCore = new GameCore(level);
window.setSize(gameCore.size);
window.add(gameCore);
gameCore.requestFocus();
gameCore.gameLoop();
window.dispose();
}
}
There is a method "paint" in gameCore
@Override
public void paint(Graphics g) {
super.paint(g);
graphicsHendler.paint(g);
}
But I try to create a "menu" where you can select a level. So I create a Window object, add JPanel with a 2 buttons. After click on a button a game is supposed to start. But there is only grey JPanel in JFrame. GameLoop() is running but not painting. If I do not start a game by gameCore.gameLoop();
there is a paint()
called once after object is created.
Create a game menu:
public class Window extends JFrame {
public Window() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setTitle("Shop-Lifter");
setFocusable(true);
setVisible(true);
}
public static void main(String[] args) {
Window window = new Window();
WelcomeScreen levelChooser = new WelcomeScreen();
window.setSize(levelChooser.getPreferredSize());
window.add(levelChooser);
}
}
And button's method starting a game:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
Window w = new Window();
GameCore gc = new GameCore(LevelLoader.loadLevel("ll1.lvl"));
w.setPreferredSize(gc.size);
w.add(gc);
w.requestFocus();
w.pack();
gc.gameLoop();
}
Most probably gc.gameLoop()
method is a blocking call, which blocks the Event Dispatcher Thread (EDT). If this is the case, you should do it in a separate thread. Another way to do it is to use active rendering.
See the following links:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.