问题描述
我想检查输入到我的JTextField1
的输入是否等于下面显示的示例图片,该怎么做?
I want to check if the input entered to my JTextField1
equal to shown sample picture below, how to do that?
我只能检查是否通过输入以下代码来输入数字以尝试阻止并捕获NumberFormatException
I can only check if numbers entered by putting below code in to try block and catch NumberFormatException
try {
taxratio = new BigDecimal(jTextField1.getText()); }
}
catch (NumberFormatException nfe) {
System.out.println("Error" + nfe.getMessage());
}
推荐答案
以下是两个选项:
带有InputVerifier
的JTextField
.除非其内容具有指定的格式,否则该文本字段不会产生焦点.
A JTextField
with an InputVerifier
. The text field will not yield focus unless its contents are of the form specified.
JTextField textField = new JTextField();
textField.setInputVerifier(new InputVerifier() {
@Override
public boolean verify(JComponent input) {
String text = ((JTextField) input).getText();
if (text.matches("%\\d\\d"))
return true;
return false;
}
});
textField.setText("% ");
带有MaskFormatter
的JFormattedTextField
.文本字段将不接受与指定的掩码不符的键入字符.如果希望在没有输入的情况下显示默认数字,则可以将占位符设置为数字.
A JFormattedTextField
with a MaskFormatter
. The text field will not accept typed characters which do not comply with the mask specified. You ca set the placeholder character to a digit if you want a default number to appear when there is no input.
MaskFormatter mask = new MaskFormatter("%##");
mask.setPlaceholderCharacter(' ');
JFormattedTextField textField2 = new JFormattedTextField(mask);
这篇关于JTextField特定格式检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!