Reputation: 1
I am working on a video game in Java that so far has a main menu class and a class for the game. As I have it set up right now, each class uses its own JFrame, which means that when the user clicks "start game", the main menu JFrame closes and the games JFrame opens. Obviously this is not ideal and I would like to have both classes use the same JFrame, however I really don't know how to go about this and internet searches have not been helpful.
The class for my main menu is:
public class Frame extends javax.swing.JFrame {
...
}
I have it set up right now so that my Game class imports my Frame class, but when I try to make the JFrame display elements from my game nothing comes up. So my question is:
How do I use one single JFrame across multiple classes?
Any help is much appreciated!
Upvotes: 0
Views: 4504
Reputation: 347184
Rather then needing to pass a reference of the main frame to each of the child panels, which might expose parts of the program you don't want them to have access to (as an example), you should use something like a CardLayout and use the main frame as the main display hub, switching out the panels as you need to
Check out How to use CardLayout for more examples
Upvotes: 1
Reputation: 297
Use cardLayout to switch panels http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html
Upvotes: 0
Reputation: 752
You should use just one frame at overall game. And there should be many JPanels for different contents.
Deciding content and switching should be like this :
switch( currentState ) {
case introduction:
setContentPane(new IntroductionPanel());
break;
case insideGame:
setContentPane( new GamePanel() );
...
...
...
}
Upvotes: 0
Reputation: 181
Rather than having each class be its own frame, you can have one frame, with several classes manipulating it. I would probably set something up like this:
public class MainFrame extends JFrame {
public MainFrame() {
super("Cool Game!");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
public class Game {
private final MainFrame mainFrame;
public Game(final MainFrame mainFrame) {
this.mainFrame = mainFrame;
mainFrame.setContentPane(createGamePanel());
}
private JPanel createGamePanel() {
//...
}
}
public class MainMenu {
private final MainFrame mainFrame;
public MainMenu(final MainFrame mainFrame) {
this.mainFrame = mainFrame;
}
public void showMainMenu() {
mainFrame.setContentPane(createMainMenuPanel());
}
private JPanel createMainMenuPanel() {
//...
}
}
Upvotes: 0