I am having troubles in finding a solution to write a listener for a JTextField specifically to only allow integer values (No Strings 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.

有帮助吗?

解决方案 2

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

其他提示

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

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, e.g. phone number format. This provides immediate validation without having to wait for form submission or similar event.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top