Java GUI showInputDialog

Java GUI showInputDialog

如何提取选定的值??我的意思是,如果 "Vital" 被用户选择,我需要为 "Olympic"

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

我有一个以前的代码可以很好地与 showConfirmDialog 框一起工作。

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);

这很好用。

如果它为您提供文本表示,请添加一个方法将文本值转换为数字索引(如果您需要的话)。如果这些值是常量,则 O(1) 的方法是提前创建地图:

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

那就是

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

相反,如果您只做一次,请不要费心创建地图。只需遍历可能的值,直到找到 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);
}

然后调用这个方法:

int index = indexFor(selectedValue, possibleValues);