如何使用if语句中选项窗格中的信息

时间:2016-06-10 10:54:05

标签: java if-statement while-loop jframe joptionpane

我正在试图弄清楚如何为选项窗格中使用的选项指定名称/标题,以便我可以在if语句中使用它们。这是我到目前为止的代码:

int i = 0;
while(i<1){
        JFrame frame = new JFrame();
            String[] options = new String[2];
            options[0] = new String("Peat");
            options[1] = new String("Repeat");
            JOptionPane.showOptionDialog(frame.getContentPane(),"Peat and Repeat were walking on a bridge\nPeat fell off, "
                    + "who was left?","", 0,JOptionPane.INFORMATION_MESSAGE,null,options,null);
    }

你会建议我接下来做什么来完成这个“笑话”?

1 个答案:

答案 0 :(得分:1)

我认为您的问题是什么意思是如何确定用户选择了哪个选项? JOptionPane.showOptionDialog返回所选选项的索引。所以你可以这样做:

import javax.swing.*;

public class Example {

    public static void main(String[] args) {

        String[] options = {"Peat", "Repeat"};

        int selectedOption = JOptionPane.showOptionDialog(null,"Peat and Repeat were walking on a bridge\nPeat fell off, who was left?","", JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,null,options,null);

        if(selectedOption == 0) System.out.println("Peat selected");
        else System.out.println("Repeat selected");
    }
}

当用户选择&#34; Peat&#34;它将打印&#34; Peat selected&#34;。

当他们选择&#34;重复&#34;它将打印&#34;重复选择&#34;