Java swing dynamically adds components

I am new to Java Swing. I have some doubts about dynamically adding components to Swing.

Basically, I have one Main JPanel consisting of two sub JPanels (leftpanel and rightpanel) that are docked horizontally. In the left JPanel , I have JButtons , when I click on JButton show some JTextArea , JTextArea , etc. in the right JPanel . I tried the code but did not work. When I click on the button, it enters the function of the event listener, but I cannot view JLabel.

I give my code below. Look at that and correct me. thanks in advance

 package my; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; /** * * @author root */ public class myAplliwithPanel extends JFrame{ JPanel rightPanel; public myAplliwithPanel() { initGui(); } public void initGui() { JPanel mainPanel=new JPanel(); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS)); JPanel leftPanel=new JPanel(); leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS)); rightPanel=new JPanel(); rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS)); JButton dbBut=new JButton("DB"); JButton appliBut=new JButton("Appli"); appliBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JLabel label=new JLabel("dsggs"); rightPanel.add(label); } }); JButton backendBut=new JButton("Backend"); leftPanel.add(dbBut); leftPanel.add(appliBut); leftPanel.add(backendBut); mainPanel.add(leftPanel); mainPanel.add(rightPanel); add(mainPanel); setTitle("System Manger"); setSize(400, 400); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main(String args[]) { SwingUtilities.invokeLater(new Runnable() { public void run() { myAplliwithPanel myObj = new myAplliwithPanel(); myObj.setVisible(true); } }); } } 
+8
java dynamic swing components
source share
3 answers

You need to call revalidate after adding (or removing) components:

 rightPanel.add(label); rightPanel.revalidate(); 

gotta do the trick.

+19
source share

Call

 rightPanel.revalidate(); rightPanel.repaint(); 

after adding

+11
source share

just add this line after adding the label

rightPanel.updateUI ();

when you add any component at runtime, you need to update ui with this method.

+3
source share

All Articles