Home > database >  Java GUI showInputDialog
Java GUI showInputDialog

Time:11-14

how can i extract the selected value?? i mean if "Vital" is selected by user , i need to get value 0, or value 1 for "Olympic"

Object[] possibleValues = { "Vital", "Olympic", "Third" };
Object selectedValue = JOptionPane.showInputDialog(null,
"Choose one", "Input",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);

i had a previous code which worked fine with a showConfirmDialog box.

int choice = JOptionPane.showConfirmDialog(null, "Click Yes for Rectangles, No for Ovals");
    if (choice==2)
    {
        return ;
    }
    
    if (choice==0) 
    {
        choice=5;
        
    }
    if (choice==1)
    {
        choice=6;
    }

    Shapes1 panel = new Shapes1(choice);

this worked fine.

CodePudding user response:

If it is giving you the text representation, add a method to convert the text value to a numerical index if that's what you need. An O(1) way of doing this would be to create a map ahead of time if these values are constant:

Map<String, Integer> valueToIndex = new HashMap<>();
valueToIndex.put("Vital", 0);
valueToIndex.put("Olympic", 1);
valueToIndex.put("Third", 2);

Then it's just

int index = valueToIndex.get((String) selectedValue)

If instead it's something you'll only be doing once, don't bother creating the map. Just iterate over the possible values until you find the index of selectedValue

int indexFor(Object selectedValue, Object possibleValues) {
    for (int i = 0; i < possibleValues.length; i  ) {
        if (possibleValues[i].equals(selectedValue)) {
            return i;
        }
    }
    throw new RuntimeException("No index found for "   selectedValue);
}

And then call this method:

int index = indexFor(selectedValue, possibleValues);
  • Related