BFreeman BFreeman - 8 days ago 6
Java Question

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

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?

Answer

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());
Comments