简体   繁体   中英

JTextfield Listener for Integers

I am having troubles in finding a solution to write a listener for a JTextField specifically to only allow integer values (No String s allowed). I've tried this recommended link on Document Listener, but I don't know what method to invoke etc.

I've never used this type of Listener before, so could anyone explain how I could write a listener on a JTextField to only allow integer values that can be accepted?

Basically after I click a JButton , and before the data is extracted out onto a variable, then Listener will not allow it to be processed until an integer is inputted.

Thanks very much appreciated.

You don't want a listener, you want to get the text from the JTextField and test if it is an int .

if (!input.getText().trim().equals(""))
{
    try 
    {
        Integer.parseInt(myString);
        System.out.println("An integer"):
    }
    catch (NumberFormatException) 
    {
        // Not an integer, print to console:
        System.out.println("This is not an integer, please only input an integer.");
        // If you want a pop-up instead:
        JOptionPane.showMessageDialog(frame, "Invalid input. Enter an integer.", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

You could also use a regex (a little bit of overkill, but it works):

boolean isInteger = Pattern.matches("^\d*$", myString);

You don't want a document listener. You want an ActionListener on the submit/ok button.

Make sure that listener is created with a handle to the JTextField, then put this code in the actionPerformed call:

int numberInField;
try {
  numberInField = Integer.parseInt(myTextField.getText());
} catch (NumberFormatException ex) {
  //maybe display an error message;
  JOptionPane.showMessageDialog(null, "Bad Input", "Field 'whatever' requires an integer value", JOptionPane.ERROR_MESSAGE);
  return;
}
// you have a proper integer, insert code for what you want to do with it here

how I could write a listener on a JTextField to only allow integer values that can be accepted?

You should be using a JFormattedTextField or a Document Filter .

JFormattedTextField example:

public static void main(String[] args) {
    NumberFormat format = NumberFormat.getInstance();
    format.setGroupingUsed(false);
    NumberFormatter formatter = new NumberFormatter(format);
    formatter.setValueClass(Integer.class);
    formatter.setMinimum(0);
    formatter.setMaximum(Integer.MAX_VALUE);
    JFormattedTextField field = new JFormattedTextField(formatter);
    JOptionPane.showMessageDialog(null, field);
}

JFormattedTextField works well for restricting input. In addition to limiting input to numbers, it is capable of more advanced use, eg phone number format. This provides immediate validation without having to wait for form submission or similar event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM