JTextField Specific format checking

风流意气都作罢 提交于 2020-01-03 05:56:08

问题


I want to check if the input entered to my JTextField1 equal to shown sample picture below, how to do that?

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());
        }


回答1:


Here are two options:

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("%  ");

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);


来源:https://stackoverflow.com/questions/23471121/jtextfield-specific-format-checking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!