You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java GUI中如何获取JOptionPane.showInputDialog选中选项对应的索引值

实现方案

JOptionPane.showInputDialog 传入选项数组时,返回值是用户选中的选项本身而非索引,你只需要将返回值和原选项数组匹配就能拿到对应索引,具体实现如下:

import java.util.Arrays;
import javax.swing.JOptionPane;

public class GetInputIndex {
    public static void main(String[] args) {
        Object[] possibleValues = { "Vital", "Olympic", "Third" };
        Object selectedValue = JOptionPane.showInputDialog(null,
                "Choose one", "Input",
                JOptionPane.INFORMATION_MESSAGE, null,
                possibleValues, possibleValues[0]);
        
        // 先判断用户是否点击取消/关闭弹窗
        if (selectedValue == null) {
            // 对应你之前showConfirmDialog的取消逻辑,直接返回即可
            return;
        }
        
        // 获取选中项对应索引
        int selectedIndex = Arrays.asList(possibleValues).indexOf(selectedValue);
        
        // 后续业务逻辑示例,和你之前confirm弹窗的用法对齐
        if (selectedIndex == 0) {
            // 选中Vital的处理逻辑
            System.out.println("选中Vital,索引为:" + selectedIndex);
        } else if (selectedIndex == 1) {
            // 选中Olympic的处理逻辑
            System.out.println("选中Olympic,索引为:" + selectedIndex);
        }
    }
}

注:该方案仅适用于选项数组中无重复元素的场景,若存在重复值会返回第一个匹配项的索引。如果不想依赖Arrays工具类,也可以手动遍历数组匹配:

int selectedIndex = -1;
for (int i = 0; i < possibleValues.length; i++) {
    if (possibleValues[i].equals(selectedValue)) {
        selectedIndex = i;
        break;
    }
}

内容的提问来源于stack exchange,提问作者GreenMaths

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 00:54:05