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?
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.
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.
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.
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();
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());
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