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 sc开发者_如何学编程rollerpane 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();
}
});
精彩评论