【问题标题】:Comparing values of two JComboBoxes比较两个 JComboBoxes 的值
【发布时间】:2013-04-04 16:29:56
【问题描述】:

快速提问。我有两个 JComboBox 填充了从 2010 年到 2018 年的一串年份。一个组合框与“开始日期”标签相关联,一个组合框与“结束日期”标签相关联。我想确保在“结束日期”中选择的年份小于在“开始日期”中选择的年份。我已经查找了有关如何比较值的方法是组合框,但我只是找不到适合我的具体示例的方法。

这里有一些代码:

String[] YEARS = {"Select a Year", "2010", "2011", "2012", "2013", "2014", 
    "2015", "2016", "2017", "2018",};

//Start Date
yearLong = new JComboBox(YEARS);
     c.fill = GridBagConstraints.HORIZONTAL;
     c.gridx = 3;
     c.gridy = 1;
     c.gridwidth = 1;
     yearLong.setSelectedItem(Integer.toString(year));
     pane.add(yearLong, c);
//End Date
         yearLong1 = new JComboBox(YEARS);
     c.fill = GridBagConstraints.HORIZONTAL;
     c.gridx = 3;
     c.gridy = 3;
     c.gridwidth = 1;
     pane.add(yearLong1, c);

为了向你证明我已经尝试了一些东西,到目前为止我已经这样做了以进行错误检查:

 //Checks to see if the End Date precedes the Start Date
         } else if ((yearLong.getSelectedItem() > yearLong1.getSelectedItem())) {
             JOptionPane.showMessageDialog(null,  "Error 10: The End Date cannot precede the Start Date.",
             "Error!",
             JOptionPane.ERROR_MESSAGE);
             return;
         }

但是,我不断收到一条错误消息,说 > 操作不能在那里使用。我知道 == 操作可以,所以我不确定我做错了什么?

像往常一样,感谢您的帮助!

【问题讨论】:

    标签: java string swing jcombobox gridbaglayout


    【解决方案1】:

    错误的原因是getSelectedItem() 实际上返回了Object,它没有定义运算符>

    由于您使用字符串填充了组合,因此在比较日期时应该将字符串转换为整数。您可以使用Integer.parseInt() 方法。只需确保正确处理 "Select a Year" 字符串即可。如果需要,您还可以使用整数填充组合框,它在其构造函数中接受 Object 数组。有关更多详细信息和示例,请参阅How to Use Combo Boxes

    【讨论】:

    • 是的,不幸的是我不确定这意味着什么。我会在哪里使用这种方法?
    • @user2221125 只需将所选项目String 转换为intint year = Integer.parseInt(yearLong.getSelectedItem().toString());
    猜你喜欢
    • 1970-01-01
    • 2012-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多