【问题标题】:Unable to select item from combobox无法从组合框中选择项目
【发布时间】:2016-06-26 23:03:34
【问题描述】:

我已经实现了ActionListener,这样我的舰船列表就会根据国家和舰船类型而变化,但问题是我无法选择任何舰船。

关于我可能出错的地方有什么想法吗?

private class ShipNameListener implements ActionListener
{   
    public ShipNameListener()
    {
        view.setShipNameListener(this);
    }   

    @Override
    public void actionPerformed(ActionEvent arg0) 
    {           
        if (view.getNationComboBox().getSelectedItem() == "USA")
        {
            if (view.getShipTypeComboBox().getSelectedItem() == "Battleship")
            {
                view.setShipList(lists.getUSABattleships());
            }
            else if (view.getShipTypeComboBox().getSelectedItem() == "CV")
            {
                view.setShipList(lists.getUSACVs());
            }
            else if (view.getShipTypeComboBox().getSelectedItem() == "Destroyer")
            {
                view.setShipList(lists.getUSADestroyers());
            }
            else if (view.getShipTypeComboBox().getSelectedItem() == "Cruiser")
            {
                view.setShipList(lists.getUSACruisers());
            }
        }           
    }       
}

以上是Controller类中的ActionListener

public void setShipNameListener(ActionListener al) 
{
    comboBoxNation.addActionListener(al);
    comboBoxShipType.addActionListener(al);
    comboBoxShipName.addActionListener(al);     
}

以上是View类中的setter。

【问题讨论】:

    标签: java swing combobox


    【解决方案1】:

    不要使用== 进行对象比较。您只使用== 进行原始比较。

    对于对象,使用equals(...) 方法。

    【讨论】:

    • 该死!你很快我正要发布相同的答案
    • 哦,是的,我完全忘记了对字符串使用 equals(...)。
    • 好吧,它仍然没有解决问题。我仍然无法选择任何船只:(
    • 然后你需要单步执行逻辑来确定为什么代码没有按预期执行。使用调试器或开始添加 System.out.printnln(...) 语句以查看逻辑流程。
    猜你喜欢
    • 2013-12-04
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-28
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    相关资源
    最近更新 更多