Adding components dynamically to JPanel

How can I dynamically add components to jpanel? I have an add button, when I click the button, the components must be added to JPanel.

my question is that adding a text box and a button to jpanel, when I click the add button, the user can click the add button any number of times according to what I have to add them to jpanel. I added to scrollerpane in jpanel and the jpanel layout manager is set to null.

+3
source share
2 answers

Just as you always do, except that you have to call:

panel.revalidate();

when you are done, as the container is already implemented.

+5

ActionListener, :

JPanel myJPanel = new JPanel();

...

b = new Button("Add Component");
b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        JLabel someLabel = new JLabel("Some new Label");
        myJPanel.add(someLabel);
        myJPanel.revalidate();
    }
});
+4

Source: https://habr.com/ru/post/1762258/


All Articles