【问题标题】:Is there a way to get the JOptionPane drop down menu to output numbers for the selected choice?有没有办法让 JOptionPane 下拉菜单输出所选选项的数字?
【发布时间】:2018-11-30 03:17:33
【问题描述】:

好吧,我的措辞可能有点混乱,但让我解释一下。

String[] choices = { "John", "Bob", "Jenny"};
String input = (String) JOptionPane.showInputDialog(null, "Choose who you want to trade with",
    "", JOptionPane.QUESTION_MESSAGE, null, choices,choices[1]);
    System.out.println(input);

我从一些 java 教程网站上获得了基本下拉菜单的代码。发生的情况是,输出只是名称,而不是我在互联网上找到的 JOptionPane 之类的输出为数字的按钮:

Object[] options = {"Clothes", "Food", "Repair equipment", "Leave the shop"};
    int Store = JOptionPane.showOptionDialog(null, "WELCOME TO THE GENERAL GOODS STORE, WHAT WOULD YOU LIKE\n                                                 you have $" + money, "Welcome",
            JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,
            null, options, options[0]);

很难做出响应用户选择的 if 语句。就这样没有人说只做一个 input.equals("John") 之类的事情,名称将是随机的,并且在它们之前有不同的短语,这会使它更难做到。好的,希望这有一定的意义,而不仅仅是一个令人困惑的混乱。如果需要,我可以澄清某些问题。

【问题讨论】:

    标签: java swing joptionpane


    【解决方案1】:

    您可以将任何组件添加到 JOptionPane,因此您可以添加包含以下内容的 JPanel:

    1. 带有消息的 Jlabel
    2. JComboBox

    基本代码是:

    JPanel panel = new JPanel( new BorderLayout() );
    panel.add(new JLabel("Choose who you want to trade with"), BorderLayout.PAGE_START);
    panel.add(comboBox, BorderLayout.PAGE_END);
    
    int result = JOptionPane.showConfirmDialog(
        frame, // use your JFrame here
        panel, 
        "Use a Panel",
        JOptionPane.YES_NO_OPTION,
        JOptionPane.PLAIN_MESSAGE);
    
    if(result == JOptionPane.YES_OPTION)
    {
        int index = comboBox.getSelectedIndex();
    }
    else
    {
        System.out.println("Canceled");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-14
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 2017-08-08
      • 2019-01-21
      相关资源
      最近更新 更多