How do you validate a text field so that it can only accept number between 1 and 100? I want to input numbers between 1 and 100 into the text field txtSeatNo. When the button btnContinue is clicked I then want it to make sure that there is a number between 1 and 100 in the text field. I am using Netbeans and have a simple GUI.
Asked
Active
Viewed 7,079 times
0
-
1Netbeans has absolutely nothing to do with it. What GUI toolkit are you using? JavaFX? What is your code? – fge Mar 19 '15 at 11:16
-
without code or context: `boolean isValid = (value >= 1 && value <= 100 ? true : false);` – Albert Mar 19 '15 at 11:19
-
You might have a look at the [InputVerifier](https://docs.oracle.com/javase/7/docs/api/javax/swing/InputVerifier.html). – SubOptimal Mar 19 '15 at 11:31
-
@Albert why the ternary operator at all? Just the expression is enough – fge Mar 19 '15 at 11:36
-
@fge, because I don't know the context, not even how he takes the `value`, or whether is an `int`. But, yes... sole expression is enough xD – Albert Mar 19 '15 at 11:45
2 Answers
1
Find a simplified example how to use a InputVerifier
on a JTextFiled
.
public class VerifierTest extends JFrame {
void createAndShowGUI() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JTextField tf1 = new JTextField(3);
// you can leave the field only it the verifier retruns true
tf1.setInputVerifier(new RangeVerifier());
JTextField tf2 = new JTextField(3);
panel.add(new JLabel("input [1..100]: "));
panel.add(tf1, BorderLayout.NORTH);
panel.add(new JLabel("some other input"));
panel.add(tf2, BorderLayout.SOUTH);
this.add(panel);
this.setSize(300, 60);
this.setVisible(true);
}
class RangeVerifier extends InputVerifier {
@Override
public boolean verify(JComponent input) {
JTextField tf = (JTextField) input;
boolean check = false;
// check if the input contains only one till three digits
// alternatively you could use a JFormattedTextField instead
// of a plain JTextField, then you could define an input mask
if (tf.getText().matches("^[0-9]{1,3}$")) {
int parseInt = Integer.parseInt(tf.getText());
// check if the number is in the range
check = parseInt >= 1 && parseInt <= 100;
};
if (check) {
tf.setBackground(Color.GREEN);
} else {
tf.setBackground(new Color(0xff8080));
}
return check;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new VerifierTest().createAndShowGUI();
}
});
}
}

SubOptimal
- 22,518
- 3
- 53
- 69
0
Assuming that you are using swing on netbeans and not matice, what you are lokking for is a JSpinner and not a JTextField. Here's a link where you can find an answer to your question : Click on me !
But if for a x/y raison you really want to use a JTextField you could use Integer's method to obtain the numeric value and then check (value > 0 && value <= 100) this value. (all that maybe in an event listener ?).