问题
I'm sorry if the title is worded a bit incorrectly.
I have recently started a new Game project, and have thought about the use of multiple JFrame
s in Java.
The reason being is my game has 2 JFrame
s:
1) Main Menu ( which is a singleton)
2) Battle.
Now the MainMenu JFrame
will initialize the Battle JFrame
on its own EDT, and then hide itself via setVisible(false)
,when the game is over setVisible(true)
can be called from Battle frame on the MainMenu frame singleton.
NB: The reason I did this was so MainMenus EDT could be reused for Battle JFrame
thus there is only 1 EDT but 2 JFrames. To prevent the Battle frame from being active (after being closed because on same EDT) I do setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Question:
Is this allowed or is there a better way?
I thought of a CardLayout
, but because a new GamePanel
will have to be created each time user presses Start JButton
I cannot initiate a single instance and set that as the card
The reason for asking is I know when doing game programming in Java you do alot of things not consider good practice (like setting locations and overall not using a LayoutManager)
To help clarify in my MainMenu UI inside an actionPerformed() method of Start Game JButton
I have:
class MainMenu extends JFrame implements ActionListener {
...
public void actionPerformed(..){
NarutoGame narutoGame = null;
narutoGame = new NarutoGame(...);
narutoGame.setVisible(true);//running in MainMenu EDT
//set this panels containing frame (MainMenu) to not visible
}
...
MainMenu getInstance() {
...
}
}
When the game is over in Battle JFrame:
class BattleField extends JFrame {
...
private void gameOver() {
MainMenu.getInstance().setVisible(true);
dispose();//dipsose of Battle JFrame
}
...
}
回答1:
To foster the willing suspension of disbelief, as well as for simple variety, games often push user interface design in novel ways. In practice, the appeal of multiple frames may not outweigh the risk. In addition to the well-known problems cited here, I would add the nightmare adduced here.
If CardLayout
is inappropriate, Buttons is an example that simply invokes removeAll()
in resetGame()
.
来源:https://stackoverflow.com/questions/12757632/multiple-jframes-for-game-scenario