在我的Swing应用程序中,用户必须插入数字和值,然后才能切换到下一个窗口.现在作为一个干净的程序,我检查每个输入是否有效,如果没有,则显示错误消息,下一个窗口不打开.
该检查的结构如下(示例):
Button buttonToOpenNextWindow = new JButton("next");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(checkValidty){
// (...)
new WindowA();
frame.dispose(); // (*)
}
}
});
Run Code Online (Sandbox Code Playgroud)
(*)注意:我知道多个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;
}
Run Code Online (Sandbox Code Playgroud)
这完全符合我的要求,但代码本身非常难看,因为有多个输入选项,该方法获得200,300或更多行(因为我不仅检查它是否是一个数字,而且如果数字有意义在程序逻辑的上下文等).是否有Swing -own方法来检查这些事情?或者有谁更好地了解如何使用拆分方法实现这一功能?
Rei*_*eus 16
一种解决方案是使用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);
Run Code Online (Sandbox Code Playgroud)
我更喜欢使用改进版JFormattedTextField.通过改进我的意思是更好的插入符号行为,验证每次更改以提供即时用户反馈(例如,当输入无效时更改背景颜色),.... 结合一个禁用的按钮,直到输入有效.
"点击按钮并看到错误消息"的主要好处是:
InputVerifier只是避免改变焦点Formats(对于日期,双精度,整数,范围......),你几乎可以处理任何情况FormatS,容易调节以不同Locale小号JFormattedTextField.所有解析代码都包含在格式中,您可以简单地使用JFormattedTextField#getValueJFormattedTextField.您知道使用的值getValue是有效值| 归档时间: |
|
| 查看次数: |
13659 次 |
| 最近记录: |