Question

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

enter image description here

Était-ce utile?

La solution

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);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top