Question

I'm fairly new to Java Swing and I'm currently trying to figure out how to make a catch error for a combo box. It was fairly easy with a text box where I could simply .getText() and .equals() it to a value I wanted it to catch for, such as

if(!textFrame.getText().trim().equals("")){
    do Stuff
}else{
    errorMessage.setText("You need to fill that field");
}

How do I do this same thing, but with a combo box? Something along the lines of:

if(!comboBox.getScrollValue().equals("Value")){
    do Stuff
}else{
    errorMessage.setText("You need to select a thingy");
Was it helpful?

Solution

You can use JComboBox.getSelectedItem() method:

// use VALUE.equals(comboBox.getSelectedItem()) to avoid NullPointerException
if(!"Value".equals(comboBox.getSelectedItem())){

More about JComboBox you can read here: http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top