【问题标题】:Java GUI showInputDialogJava GUI 显示输入对话框
【发布时间】:2021-12-25 21:38:12
【问题描述】:

如何提取选定的值?我的意思是如果用户选择了 "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);

这很好。

【问题讨论】:

    标签: java swing user-interface jframe joptionpane


    【解决方案1】:

    如果它为您提供文本表示,添加一个方法将文本值转换为数字索引,如果这是您需要的。如果这些值是恒定的,那么执行此操作的 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);
    

    【讨论】:

    • 第一个解决方案的第一行将是 HashMap valueToIndex = new HashMap(); ,除此之外,您的解决方案效果很好,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2016-04-14
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    相关资源
    最近更新 更多