2013-04-04 134 views
0

快速的问题。我有两个JComboBox用2010年至2018年的字符串填充。一个组合框与“开始日期”的标签相关联,一个组合框与“结束日期”的标签相关联。我想确保在“结束日期”中选择的年份少于“开始日期”中选定的年份。我查找了如何比较值的方法是组合框,但我无法找到具体示例的方法。比较两个JComboBoxes的值

下面是一些代码:

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

不过,我不断收到:

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

而要证明给你看,我已经尝试过的东西,我为我的错误检查迄今所做的这一个错误说,>操作不能在那里使用。我知道==操作可以,所以我不知道我在做什么错了?

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

回答

2

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

既然你填入字符串连击,你应该比较字符串中的日期时,转换为整数。您可以使用Integer.parseInt()方法。只要确保你处理“Select a Year”字符串适当。如果需要,您也可以用整数填充组合框,它在其构造函数中接受数组Object。有关更多详细信息和示例,请参见How to Use Combo Boxes

+0

是啊,可惜我不知道这意味着什么。我会在哪里使用这种方法? – user2221125 2013-04-04 19:11:38

+0

@ user2221125所选择的项目是'String'只是转换为'int':'INT年=的Integer.parseInt(yearLong.getSelectedItem()的toString());' – tenorsax 2013-04-04 20:29:19