Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change JPanel inside a JFrame on the fly?

To put it simple, there's a simple java swing app that consists of JFrame with some components in it. One of the components is a JPanel that is meant to be replaced by another JPanel on user action.

So, what's the correct way of doing such a thing? I've tried

panel = new CustomJPanelWithComponentsOnIt(); parentFrameJPanelBelongsTo.pack(); 

but this won't work. What would you suggest?

like image 763
yanchenko Avatar asked Oct 20 '08 11:10

yanchenko


People also ask

How do you switch between panels in Java?

If you want to switch between two panels add those panels into another JPanel and use cardLayout. Then, before adding a JPanel remove the current one. Like this: parentPanel.

Can we change the layout of JPanel?

Each JPanel object is initialized to use a FlowLayout , unless you specify differently when creating the JPanel . Content panes use BorderLayout by default. If you do not like the default layout manager that a panel or content pane uses, you are free to change it to a different one.


2 Answers

Your use case, seems perfect for CardLayout.

In card layout you can add multiple panels in the same place, but then show or hide, one panel at a time.

like image 153
Swapnonil Mukherjee Avatar answered Oct 20 '22 20:10

Swapnonil Mukherjee


1) Setting the first Panel:

JFrame frame=new JFrame(); frame.getContentPane().add(new JPanel()); 

2)Replacing the panel:

frame.getContentPane().removeAll(); frame.getContentPane().add(new JPanel()); 

Also notice that you must do this in the Event's Thread, to ensure this use the SwingUtilities.invokeLater or the SwingWorker

like image 30
Telcontar Avatar answered Oct 20 '22 21:10

Telcontar