tags:

views:

62

answers:

2

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.

+3  A: 

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

panel.revalidate();

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

ymene
Indeed (although I don't think `repaint` is actually necessary). See the API docs for `java.awt.Container.add`.
Tom Hawtin - tackline
Before I always thought both methods were always used together, since I saw it like that in many examples.Just tried it myself and indeed, revalidating seems enough! thank you for this advice, you are right.
ymene
In this simple case of "adding" a button you will generally never need to use repaint(). However try a simple case of "removing" a button and it won't work. In this case you do need to use repaint(). My general rule is try it first with revalidate(), if it doesn't work then add a repaint();
camickr
Should have done more testing on it, thank you as well for this advise!
ymene
+1  A: 

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 MYYN
You must revalidate the container (myJPanel) after adding components if the container has already been displayed.
Steve McLeod