gpt4 book ai didi

java - JOptionPane 处理 ok、cancel 和 x 按钮

转载 作者:行者123 更新时间:2023-12-03 22:58:37 26 4
gpt4 key购买 nike

我的 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);
}
}

最佳答案

基本方法如下所示:

在@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");
}
}
}

关于java - JOptionPane 处理 ok、cancel 和 x 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24970176/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com