问题描述
在我的Swing应用程序中,用户必须插入数字和值,然后才能切换到下一个窗口。现在作为一个干净的程序,我检查每个输入是否有效,如果没有,则显示错误消息,下一个窗口不打开。
In my Swing application, the user must insert numbers and values, before switching to the next window. Now as a clean program should, I check every input if its valid or not, and if not, an error message is displayed and the next window does not open.
此检查的结构如下(示例):
The structure of this check is as following (example):
Button buttonToOpenNextWindow = new JButton("next");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(checkValidty){
// (...)
new WindowA();
frame.dispose(); // (*)
}
}
});
(*)注意:我知道多个JFrame的原理是丑陋,我正在改变这一点,但对于这个问题它是无关紧要的。
(*) Note: I know that the principle of multiple JFrames is ugly, and I'm on to change that, but for this question it's irrelevant.
现在这个问题的重点是这个 checkValidity()
,我的结构如下:
Now the focus of this question is this checkValidity()
, which I structured like this:
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 -own方法来检查这些东西?或者有没有人更好地了解如何使用拆分方法实现这一功能?
This works exactly as I want, BUT the code itself is very ugly, because having multiple input options the method gets 200, 300 or more lines long (as I do not only check if e.g. it's a number, but also if the number makes sense in context of the program logic and so on). Is there a Swing -own method to check such things? Or has anyone a better idea how to realize exactly this functionality with split methods?
推荐答案
一种解决方案是使用Swing的 InputVerifier
验证所使用的每个 JTextField
的输入。由于每个字段的验证功能相同,因此单个实例可用于所有组件:
One solution would be to use Swing's InputVerifier
to validate input for every JTextField
used. As the validation functionality is the same for each field, a single instance could be used for all components:
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:实现输入值的有效性检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!