JOptionPane 处理确定、取消和 x 按钮

use*_*568 3 java swing joptionpane

如果我不输入任何内容,我的 JOptionPane 将面临一个问题,无论我按什么(确定、取消或 x 按钮(JOptionPane 中的右上角按钮)),它都会提示我,直到我输入一个正值。但我只希望在我按下确定时出现提示。

如果我单击取消或 x 按钮(JOptionPane 中的右上角按钮),它将关闭 JOptionPane

我怎样才能做到这一点?

import javax.swing.JOptionPane;

public class OptionPane {
    public static void main(final String[] args) {
        int value = 0;
        boolean isPositive = false , isNumeric = true;
        do {
            try {
                value = Integer.parseInt(JOptionPane.showInputDialog(null,
                    "Enter value?", null));
            } catch (NumberFormatException e) {
                System.out.println("*** Please enter an integer ***");
                isNumeric = false;
            }

             if(isNumeric) {
                if(value <= 0) {
                    System.out.println("value cannot be 0 or negative");
                }

                else {
                    System.out.println("value is positive");
                    isPositive = true;
                }
            }
        }while(!isPositive);
    }
}
Run Code Online (Sandbox Code Playgroud)

blu*_*xel 6

对此的基本方法可能如下所示:

在@MadProgrammer 评论后更新。

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class DemoJOption {
    public static void main(String args[]) {
        int n = JOptionPane.showOptionDialog(new JFrame(), "Message", 
        "Title", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, 
        null, new Object[] {"Yes", "No"}, JOptionPane.YES_OPTION);

        if (n == JOptionPane.YES_OPTION) {
            System.out.println("Yes");
        } else if (n == JOptionPane.NO_OPTION) {
            System.out.println("No");
        } else if (n == JOptionPane.CLOSED_OPTION) {
            System.out.println("Closed by hitting the cross");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • `JOptionPane.showOptionPane` 不返回`一个整数,指示用户选择的选项,或者 CLOSED_OPTION 如果用户关闭对话框`,这意味着 `n == 0` 会更准确,如 `JOptionPane.YES_OPTION`可以定义为任何东西...? (2认同)