0

I have created a comboBox in Swing and I want to add items on it in another function. But the problem is that items are not displaying after calling that function:

public void addItems()
{
    combo.addItem("");
    // i want to add items here when this function is being called
    // but those items are not displaying after calling this function
    // i m calling this function on button click
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
ADESH RAJPUT
  • 131
  • 1
  • 5
  • 10

3 Answers3

3

Works for me in this SSCCE:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UnsupportedLookAndFeelException;

public class TestComboBox {

    private int count = 0;

    protected void initUI() {
        final JFrame frame = new JFrame(TestComboBox.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JComboBox comboBox = new JComboBox(new Object[] { "Something", "Stuff", "Beep" });
        JButton add = new JButton("Add item");
        add.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                comboBox.addItem("Item-" + count++);
            }
        });
        frame.add(comboBox);
        frame.add(add, BorderLayout.SOUTH);
        frame.pack();
        frame.setBounds(50, 50, 300, frame.getHeight());
        frame.setVisible(true);
    }

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
            UnsupportedLookAndFeelException {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TestComboBox().initUI();
            }
        });
    }
}
Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
2

If your combobox has a MutableComboBoxModel, you can do the following

MutableComboBoxModel model = (MutableComboBoxModel)combo.getModel();
model.addElement( elementToAdd );

This is equivalent to calling JComboBox#addItem (see below for the implementation):

public void addItem(Object anObject) {
    checkMutableComboBoxModel();
    ((MutableComboBoxModel)dataModel).addElement(anObject);
}

But I think it is a best practice to modify the model directly if you want to make changes on the model side, and not go through the view (except to provide the user the ability to edit in the view)

Robin
  • 36,233
  • 5
  • 47
  • 99
-2

you need to invoke:

repaint();
validate();
  • 4
    not, you are wrong (re)validate and repaint is for add, remove (add & remove) or modify JComponents on runtime, those methods are for LayoutManager, not for add a new Item to the JComboBox on runtime, please to delete or amend this question – mKorbel Sep 20 '12 at 07:40