JComboBox选择更改

时间:2014-12-05 18:19:19

标签: java swing combobox event-handling

每个人我都是Java GUI的新手,我遇到了JComboBox的问题,当我从组合框中删除AllItems来刷新它时,这是一个问题,这是一个问题,因为我得到所选项目详细信息和填充一个带有它们的文本框,以便在那一点上我正在获得一个空指针。 是否有任何简单的(ish)方法可以在更改所选项目时调用ComboBox上的方法,而不仅仅是在更改组合框内容时?

代码

comboBox当前方法

private void customerComboActionPerformed(java.awt.event.ActionEvent evt) {                                              

   setDetails();

} 

在组合框中设置项目的方法

public void setCustomers()
{
customerCombo.removeAllItems();
for (Customer curr : Main.getNewCustomerList().getCustomers())
{

    customerCombo.addItem(curr);
}
}

设置细节的方法

public void setDetails()
{
Customer selected = (Customer) customerCombo.getSelectedItem();
forenameText.setText(selected.getForename());
surnameText.setText(selected.getSurname());
costperkgText.setText(String.valueOf(selected.getDeliveryCost()));
line1Text.setText(String.valueOf(selected.getColAddress().getAddressLine1()));
line2Text.setText(String.valueOf(selected.getColAddress().getAddressLine2()));
cityText.setText(String.valueOf(selected.getColAddress().getCity()));
postcodeText.setText(String.valueOf(selected.getColAddress().getPostcode()));

}

2 个答案:

答案 0 :(得分:1)

您没有考虑没有选择的情况。

public void setDetails()
{
    Customer selected = (Customer) customerCombo.getSelectedItem();
    if (selected != null)
    {
        // there is a selection so use it
    }
    else
    {
        // for example, clear the text boxes
    }
}

我们还希望更改组合框的内容可能会改变其选择,因此我们不应忽略它。

答案 1 :(得分:0)

我喜欢设置旗帜。关键是要确保标志不会被误推。

private volatile boolean fire = true;

public void setItems(Object[] items) {
    try {
        fire = false; // Don't fire updates
        updateItems(items);
    } finally {
        fire = true; // always reset no matter what!
    }
}

private JComboBox create() {
    JComboBox cb = new JComboBox();
    cb.addActionListener( new ActionListener() {
        public void actionPerformed( ActionEvent e ) {
            if(fire) {
                notifyListeners(); 
            }
        }
    });
}

你必须确保多个线程不会调用它,但由于Swing不是线程安全的,所以无论如何都应该这样做。