0

I'm trying to move from a title screen into the main program. I was going to simply set a button to create a new JFrame and close the previous however upon research this is said to be bad practice and the result isn't as seamless as I would hope. Any suggestions?

Melika Barzegaran
  • 429
  • 2
  • 9
  • 25
HS'
  • 37
  • 1
  • 8

1 Answers1

4

A JFrame is a window, when you use applications they do not typically open up a new window every time you change to a new view. Instead, you should have one JFrame and set up multiple JPanels. This way you can add the correct JPanel to the JFrame when needed.

To do this:

JFrame frame = new JFrame();
frame.getContentPane().add(titlePanel); //menuPanel refers to a panel you create

Then when your button is clicked:

frame.getContentPane().removeAll();
frame.getContentPane().add(mainPanel);
frame.revalidate();
chrissukhram
  • 2,957
  • 1
  • 13
  • 13
  • Hi. Sorry for the late comment. How would I do this using an external plugin which automatically creates the JFrame : *`/** * Auto-generated main method to display this JFrame */ public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { StaffList2WithBetterSaveGUI inst = new StaffList2WithBetterSaveGUI(); inst.setLocationRelativeTo(null); inst.setVisible(true); } }); }` * – HS' Mar 21 '15 at 22:17
  • @HS' you would do ```inst.getContentPane().removeAll(); inst.getContentPane().add(mainPanel); inst.revalidate(); inst.repaint();``` – Cardinal System Jun 25 '17 at 17:25
  • @chrissukhram If I was trying to "refresh" my frame doing ```frame.add(mainPanel); //... frame.getContentPane().removeAll(); frame.add(mainPanel); frame.revalidate(); frame.repaint();``` with `mainPanel` containing multiple nested `JPanels`, would those four statements also refresh the panels? – Cardinal System Jun 25 '17 at 17:31