简体   繁体   中英

adding components dynamically in a JPanel

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.

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

panel.revalidate();

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM