Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically add Panels to other panels at runtime in Java?

Tags:

java

swing

I'm trying to get into java again (it's been a few years). I never really did any GUI coding in java. I've been using Netbeans to get started with this.

When using winforms in C# at work I use a usercontrols to build parts of my UI and add them to forms dynamically.

I've been trying to use JPanels like usercontrols in C#. I created a JPanel form called BlurbEditor. This has a few simple controls on it. I am trying to add it to another panel at run time on a button event.

Here is the code that I thought would work:

mainPanel.add(new BlurbEditor());
mainPanel.revalidate();
//I've also tried all possible combinations of these too
//mainPanel.repaint();
//mainPanel.validate();

This unfortunately is not working. What am I doing wrong?

like image 849
BFreeman Avatar asked Oct 04 '08 05:10

BFreeman


People also ask

Can you add a panel to another panel in Java?

The FlowLayout is a default layout for a JPanel. We can add most of the components like buttons, text fields, labels, tables, lists, trees, etc. to a JPanel. We can also add multiple sub-panels to the main panel using the add() method of Container class.

How do I add a panel to a frame in Java?

To add the panel to the frame, get the content pane frame from the frame object first, the call the add method passing in the panel. The pack method tells the frame to resize itself based on the preferred size of the components it contains.

Is a panel a component in Java?

A panel is a component that's used as a container for other components. The normal way to build a Swing user interface is to create a panel, add components such as labels, text boxes, and buttons to the panel, then add the panel to the content pane.


2 Answers

I was dealing with similar issue, I wanted to change the panel contained in a panel on runtime
After some testing, retesting and a lot of failing my pseudo-algorithm is this:

parentPanel : contains the panel we want to remove
childPanel : panel we want to switch
parentPanelLayout : the layout of parentPanel
editParentLayout() : builds parentPanel with different childPanel and NEW parentPanelLayout every time

parentPanel.remove(childPanel); 
editParentLayout();
parentPanel.revalidate();
parentPanel.repaint();
like image 176
Dimitris Avatar answered Sep 19 '22 13:09

Dimitris


I figured it out. The comments under the accepted answer here explain it: Dynamically added JTable not displaying

Basically I just added the following before the mainPanel.add()

mainPanel.setLayout(new java.awt.BorderLayout());
like image 35
BFreeman Avatar answered Sep 19 '22 13:09

BFreeman