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". 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.
Since you populated the combos with strings, you should convert the strings to integers when comparing the dates. You can use Integer.parseInt()
method. 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. See How to Use Combo Boxes for more details and examples.