如何使用JOptionPane的响应?

时间:2014-06-21 11:39:38

标签: java joptionpane

这是我第一次使用确认框,我想要一些关于如何使用它的建议,我想使用"是或否"的用户输入。但不知道怎么做?如果我想在if语句中引用来自JOptionPane的输入,那会怎样呢?

JOptionPane.showConfirmDialog(null, "Click yes to terminate. ", "TERMINATE SIMULATION?", JOptionPane.YES_NO_OPTION);

谢谢。

2 个答案:

答案 0 :(得分:3)

使用它像:

   int result = JOptionPane.showConfirmDialog(null, "Click yes to terminate. ", "TERMINATE SIMULATION?", JOptionPane.YES_NO_OPTION);

    if (JOptionPane.YES_OPTION == result) {
                System.out.println("yes");
     } else if (JOptionPane.NO_OPTION == result) {
                System.out.println("No");
     }else{
            System.out.println("Nothing");
    }

还可以在下面找到选项类型和返回值(来自源代码):

 /**
     * Type meaning Look and Feel should not supply any options -- only
     * use the options from the <code>JOptionPane</code>.
     */
    public static final int         DEFAULT_OPTION = -1;
    /** Type used for <code>showConfirmDialog</code>. */
    public static final int         YES_NO_OPTION = 0;
    /** Type used for <code>showConfirmDialog</code>. */
    public static final int         YES_NO_CANCEL_OPTION = 1;
    /** Type used for <code>showConfirmDialog</code>. */
    public static final int         OK_CANCEL_OPTION = 2;

    //
    // Return values.
    //
    /** Return value from class method if YES is chosen. */
    public static final int         YES_OPTION = 0;
    /** Return value from class method if NO is chosen. */
    public static final int         NO_OPTION = 1;
    /** Return value from class method if CANCEL is chosen. */
    public static final int         CANCEL_OPTION = 2;
    /** Return value form class method if OK is chosen. */
    public static final int         OK_OPTION = 0;
    /** Return value from class method if user closes window without selecting
     * anything, more than likely this should be treated as either a
     * <code>CANCEL_OPTION</code> or <code>NO_OPTION</code>. */
    public static final int         CLOSED_OPTION = -1;

另外,不要直接检查响应值,例如if(1==result) NO_OPTION,请始终使用JoptionPane类中的常量。

答案 1 :(得分:0)

如果您想了解有关Swing Dialog的更多信息,请查看 Swing Tutorial 的以下部分,其中详细解释了这些内容。