javaswingjcombobox

Save items from JComboBox to text file


I have a JComboBox (cmbCourse) that uses the Scanner class to add items ('Science', 'Psychology', 'Law') from a text file. Now I want to create an if statement that gets the selected item from the comboBox but I'm having trouble, it should be something like this:

if(cmbCourse.getSelectedItem() == Science) {
...
}

I get an error saying that 'Science' can't be resolved to a variable. How do I access the items that come from the text file and compare them to the items from the comboBox?


Solution

  • Assuming you are adding strings to the combobox, getSelectedItem should return a string. However, it returns said string as an object. The comparison should work anyway, just good to know.

    It's important to note that in Java, strings do NOT compare correctly using ==, as this is object equals. You MUST use .equals() for correct string comparison. Also, null check in case nothing is selected.

    if( cmbCourse.getSelectedItem() != null && cmbCourse.getSelectedItem().equals( "Science" )
    {
      // do stuff
    }