gpt4 book ai didi

java - 在 Java 中按下按钮之前验证输入

转载 作者:行者123 更新时间:2023-12-01 10:44:58 26 4
gpt4 key购买 nike

我有一个可以自行创建的对话框,应该检查用户的输入。目前,我可以让它验证空输入,并在它是整数时正确解析用户输入,但是在使用字符串进行验证时,我不断收到 NumberFormatException。添加 try、catch 确实阻止了 JVM 崩溃,但输入为 null。

public void initDialog() {
dPanel = new JPanel();
dPanel.setLayout(new BoxLayout(dPanel, BoxLayout.Y_AXIS));
JLabel invalidInput = new JLabel("");
String[] options = {"OK"};
dPanel.add(new JLabel("Game default target is 101, enter a number below to change it"));
dPanel.add(new JLabel("Leave blank to start with the default"));
dPanel.add(invalidInput);
JTextField text = new JTextField("");
text.requestFocusInWindow();
dPanel.add(text);

int changeGameTarget = JOptionPane.showOptionDialog(null, dPanel, "Dice Game", JOptionPane.NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);

dialogHandler(changeGameTarget, text, invalidInput);

text.setText("");
}

对话框处理方法

   public boolean dialogHandler(int op, JTextField text, JLabel nonDigit) {

String s = text.getText();

try {
if (op == JOptionPane.OK_OPTION) {
if (s.isEmpty()) {
target = 101;
} else {
target = Integer.parseInt(s);
}
}
} catch (NumberFormatException ex){
nonDigit.setText("This is not a number");
return false;
}

return true;
}

最佳答案

让我们在解析中使用 Try-Catch 作为 if-else 并将方法更改为 boolean 值,这样您就可以将其作为主程序中的循环。

public boolean dialogHandler(int op, JTextField text, JLabel nonDigit) {

String s = text.getText();

if (op == JOptionPane.OK_OPTION) {
if (s.isEmpty()) {
return false; // If the text is empty we return false for the flag.
} else {
try {
target = Integer.parseInt(s);
return true; // If parse was succesful, we return true for the flag.
} catch (Exception e) {
return false; // If the exception happened, return false for the flag.
}
}
} else if (op == JOptionPane.CLOSED_OPTION) {
System.exit(0);
}
}

然后我们改变main:

boolean flag;
do {
int changeGameTarget = JOptionPane.showOptionDialog(null, dPanel, "Dice Game", JOptionPane.NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
flag = dialogHandler(changeGameTarget, text, invalidInput);
} while (!flag);

关于java - 在 Java 中按下按钮之前验证输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34239485/

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