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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With