add items runtime on combobox in java

六月ゝ 毕业季﹏ 提交于 2019-12-02 15:21:15

问题


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
}

回答1:


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();
            }
        });
    }
}



回答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)




回答3:


you need to invoke:

repaint();
validate();


来源:https://stackoverflow.com/questions/12507926/add-items-runtime-on-combobox-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!