当用户输入无效或根本没有输入时,我试图发送错误 JOptionPane。我试图用一个 try/catch 块和一个 NumberFormatException 来做到这一点,但在我看来,该块被忽略了,但这不可能。
import javax.swing.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.lang.NumberFormatException;
public abstract class Input extends JFrame implements ActionListener {
public static void main(String[] args) throws NumberFormatException {
//implementation of the GUI with JTexFields etc.
try {
button.addActionListener(e -> {
Label.setText(" ");
int Num1 = 5;
int Num2 = Integer.valueOf(Field1.getText());
if (Num1 <= 0) {
//something;
}
//calculate with input
});
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,
"Please watch out for your input.",
"Input error",
JOptionPane.ERROR_MESSAGE);
}
}
}
很抱歉,代码可能不符合代码约定,但我删除了所有不重要的部分,因此,我可能使代码变得“丑陋”。
将 try catch 块放在动作侦听器中。动作侦听器是一个不同的类,因此您当前的 try catch 块不会在其中捕获异常。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句