【发布时间】:2012-10-11 10:54:52
【问题描述】:
在我的 Swing 应用程序中,用户必须在切换到下一个窗口之前插入数字和值。现在作为一个干净的程序应该,我检查每个输入是否有效,如果不是,则会显示一条错误消息并且下一个窗口不会打开。
此检查的结构如下(示例):
Button buttonToOpenNextWindow = new JButton("next");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(checkValidty){
// (...)
new WindowA();
frame.dispose(); // (*)
}
}
});
(*) 注意:我知道多 JFrame 的原理是丑陋的,我正在改变它,但对于这个问题它是无关紧要的。
现在这个问题的重点是这个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 或更多行(因为我不仅检查它是否是一个数字,而且如果number 在程序逻辑的上下文中是有意义的等等)。是否有 Swing 自己的方法来检查这些事情?或者有谁更好地了解如何使用拆分方法来准确实现此功能?
【问题讨论】: