在我的 Swing 应用程序中,用户必须在切换到下一个窗口之前插入数字和值。现在,作为一个干净的程序,我会检查每个输入是否有效,如果无效,则会显示一条错误消息,并且不会打开下一个窗口。
此检查的结构如下(示例):
Button buttonToOpenNextWindow = new JButton("next");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(checkValidty){
// (...)
new WindowA();
frame.dispose(); // (*)
}
}
});
(*) 注意:我知道多个 JFrames 的原理很丑陋,我打算改变它,但对于这个问题来说它是无关紧要的。
现在这个问题的重点是这个checkValidity()
,我的结构是这样的:
private boolean checkValidity(){
// check input 1
try{
Integer.parseInt(textField1.getText());
}catch (NumberFormatException e){
new ErrorDialog("input 1 is invalid!"); // own implemented dialog
return false;
}
// check input 2
try{
Integer.parseInt(textField2.getText());
}catch (NumberFormatException e){
new ErrorDialog("input 2 is invalid!"); // own implemented dialog
return false;
}
// (...)
// check input n
try{
Integer.parseInt(textField_n.getText());
}catch (NumberFormatException e){
new ErrorDialog("input n is invalid!"); // own implemented dialog
return false;
}
return true;
}
这完全符合我的要求,但代码本身非常丑陋,因为有多个输入选项,该方法会变得 200、300 或更多行(因为我不仅检查它是否是一个数字,而且还检查它是否数字在程序逻辑等上下文中有意义)。是否有 Swing 自己的方法来检查这些事情?或者有谁知道如何使用拆分方法准确实现此功能?
最佳答案
一种解决方案是使用 Swing 的 InputVerifier
来验证每个使用的 JTextField
的输入。由于每个字段的验证功能都相同,因此可以将单个实例用于所有组件:
public class MyNumericVerifier extends InputVerifier {
@Override
public boolean verify(JComponent input) {
String text = ((JTextField) input).getText();
try {
Integer.parseInt(text);
} catch (NumberFormatException e) {
return false;
}
return true;
}
}
InputVerifier verifier = new MyNumericVerifier()
textField1.setInputVerifier(verifier);
关于Java Swing : Implementing a validity check of input values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12997742/