Java Swing dynamic JComboBox

廉价感情. 提交于 2019-12-11 02:53:00

问题


I have populated a combobox B1 from database. When itemStateChanged event raises it should populate another combobox B2, but its not working.

ArrayList1 = //call method in database connection class()
for (int j = 0; j < ArrayList1.size(); j++) 
{
    if (j == 0)
    {
        combobox1.addItem("Select Any");
    }
    combobox1.addItem(ArrayList1.get(j));
}


combobox1.addItemListener(new ItemListener() 
{
    @Override
    public void itemStateChanged(ItemEvent ie) 
    {
        String catName = (String)combobox1.getSelectedItem();
        if (!catName.equalsIgnoreCase("Select Any"))
        {
            ArrayList2=//call method in DB class with cat_name as argument
            for(int i=0;i < ArrayList2.size();i++)
            {
                if (i == 0)
                {
                    combobox2.addItem("Select Any");
                }
                combobox2.addItem(ArrayList2.get(i));                   
            }                   
        }
    }           
});

first combobox gets populated from database, but after selecting any item from it second combobox keeps empty.

and why debugging this my computer hangs on?


回答1:


you have to implements ComboBoxModel and add/remove/change Items in the Model, not in the JComboBox, nor somewhere in the Array, List or Vector, sure is possible but you have to execute your code on EDT and always replace Array, List or Vector for concreted JComboBox, don't do it that this way :-)

maybe you have problem with Concurency in the Swing, maybe changes are done, but outside EDT, more about your issues pass events wrapped into invokeLater() and multiple-jcombobox




回答2:


DefaultComboBoxModel model = new DefaultComboBoxModel(yourstringarray);
                    item_combobox.setModel( model );

n ma problem get solved....




回答3:


You must read:

http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html

It will help you to deal with java comboboxes.

Seems you should use an ActionListener as event to populate second combobox.

For your debug problems you should check bug 6714678 from java bugtracker

-Dsun.awt.disablegrab=true

should solve your debug problem (since 2008)

See could not work for old jdks as on 2007 related bug 6517045 says:

after discussion we came to conclusion that this (debug on combobox events) is just one more place when it is not wise to stop in debugger (the same is true for DnD, fullscreen).



来源:https://stackoverflow.com/questions/7427511/java-swing-dynamic-jcombobox

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