2013-04-04 133 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