tags:

views:

34

answers:

2

What is the best way to restrict a JTextField input to only positive integers? Thanks!

A: 

I don't remember the exact details, but you should override onInput(..) event or something like that and in that overridden method you should test input values, if they are negative or zero, set value to blank.

gasan
+2  A: 

The best way would be to implement a DocumentFilter. The filter can check that the text contains a positive integer and otherwise prevent the text from being inserted. The link above contains an example on how to limit the length of the text, it should help you to get started.

To check if the input is a positive integer, you could use Integer.parseInt(String s);.

Carlos