Home Ask Login Register

Developers Planet

Your answer is one click away!

Michael February 2016

Dynamically add swing component to gui on click?

Purely theoretically when adding new components like that

JButton buttonAdd= new JButton("Add More");
        buttonAdd.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                  panel.add(new JComboBox<String>(data);
                  panel.add(new JTextField();

Is there way to getSelectedIndex() or getText() when u don't declare it in normal way?


h22 February 2016

Yes, you can add Swing components to the container this way. However you need to call revalidate on the panel, otherwise they may not appear instantly.

If you need to access these components after they are created, assign the value returned by constructor to the field of your object, declared inside your class. You cannot assign to the variable in the calling method as the constructors are called from the inner class.

guleryuz February 2016

there are several ways to reach dynamicaly added components to swing tree:

1st approach:


returns n'th component in the panel (Container). (n is the order, that component added to its parent (parent is panel here) ) (you need to know component's index) this way you can use ((JComboBox)panel.getComponent(3)).getSelectedIndex()

2nd approach

directly add some listeners when dynamically adding your components;

JButton b1 = new JButton("add");
b1.addActionListener(e -> {  

    JComboBox<String> color = new JComboBox<String>();
    color.addActionListener(x -> { myFormBean.setColor(color.getSelectedItem();) });

    JTextField name = new JTextField();
    name.getDocument().addDocumentListener(new DocumentListener() {
        public void removeUpdate(DocumentEvent e) {

        public void insertUpdate(DocumentEvent e) {

        public void changedUpdate(DocumentEvent e) {



this way you do not need to reach your dynamically added components.

3rd approach may be using a framework for data binding,

4rd approach ...

Post Status

Asked in February 2016
Viewed 2,777 times
Voted 12
Answered 2 times


Leave an answer

Quote of the day: live life