简体   繁体   English

比较两个JComboBox的值

[英]Comparing values of two JComboBoxes

Quick question. 快问。 I have two JComboBoxes filled with a string of years from 2010 to 2018. One combo box is associated to a label of "Start Date" and one ComboBox is associated to a label of "End Date". 我有两个JComboBox,从2010年到2018年填充了一串年。一个组合框与“开始日期”标签相关联,一个ComboBox与“结束日期”标签相关联。 I want to make sure that the year selected in the "End Date" is LESS THAN the year selected in the "Start Date". 我想确保在“结束日期”中选择的年份少于“开始日期”中选择的年份。 I've looked up ways on how to compare values is comboboxes, but I just can't find a way for my specific example. 我已经找到了如何比较值是组合框的方法,但我找不到适合我具体例子的方法。

Here's some code: 这是一些代码:

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

And to prove to you that I've tried something, I've done this so far for my error checking: 为了向你证明我已经尝试了一些东西,到目前为止我已经完成了我的错误检查:

 //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;
         }

However I keep getting an error saying that the > Operation cannot be used there. 但是我一直收到一个错误,说>操作不能在那里使用。 I know the == operation can, so I'm not sure what I'm doing wrong? 我知道==操作可以,所以我不确定我做错了什么?

As usual, thank you for your help! 像往常一样,谢谢你的帮助!

The reason for error is that getSelectedItem() actually returns Object which has no operator > defined. 错误的原因是getSelectedItem()实际上返回没有运算符>定义的Object

Since you populated the combos with strings, you should convert the strings to integers when comparing the dates. 由于您使用字符串填充组合,因此在比较日期时应将字符串转换为整数。 You can use Integer.parseInt() method. 您可以使用Integer.parseInt()方法。 Just make sure you handle "Select a Year" string appropriately. 只需确保适当地处理“选择一年”字符串。 You may also populate combo box with integers if needed, it accepts array of Object in its constructor. 如果需要,您也可以使用整数填充组合框,它在其构造函数中接受Object数组。 See How to Use Combo Boxes for more details and examples. 有关更多详细信息和示例,请参见如何使用组合框

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM