Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding components dynamically in a JPanel

Tags:

java

swing

how can i add components dynamically in a jpanel? I am having add button when i click the button the components should be added to the JPanel.

my question is that adding a textfield and button to jpanel when i click on the add button the user can click on the add button any number of times according to that i have to add them to the jpanel. i have added to scrollerpane to my jpanel,and jpanel layout manager is set to null.

like image 338
Lalchand Avatar asked Sep 20 '26 12:09

Lalchand


2 Answers

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

panel.revalidate();

when you are done, since the container is already realized.

like image 139
crusam Avatar answered Sep 22 '26 00:09

crusam


Use an ActionListener, you can use an anonymous class like this:

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();
    }
});
like image 31
miku Avatar answered Sep 22 '26 01:09

miku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!