Reputation: 131
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
}
Upvotes: 0
Views: 9267
Reputation: 36621
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)
Upvotes: 2
Reputation: 47637
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();
}
});
}
}
Upvotes: 3