Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Java Textfield ONLY NUMBERS

$
0
0
Hey, i wanted to create a Textfield where it should only be possible to put numbers from 0-999 into.
Could anybody help me with this?
I already tried it with a formattedtextfield like this:
MaskFormatter formatter = new MaskFormatter("***");
formatter.setValidCharacters("0123456789");
tf = new JFormattedTextField(formatter);


but the problem was that if i wanted to put a number with less than 3characters( 10 for example) into it
i had to write (010) a zero in front of it and it wasnt possible to easily get the text out of this textfield.
does anyone have an idea?
this is the code to read out the textfield
public void keyReleased(KeyEvent e) {
                               if(e.getKeyCode()==KeyEvent.VK_ENTER || e.getKeyCode()==KeyEvent.VK_TAB){
                                   if (tf.getText()==null || ("".equals(tf.getText()))){
                                       tf.setText("0");
                                       geschwindigkeit2 = 0;
                                    }   
                                    else{

                                        int value = Integer.parseInt(tf.getText());
                                        if (value <100 && value > 9){
                                            tf.setText("0" + String.valueOf(value)); 
                                        }
                                        if (value<10){
                                         tf.setText("00" + String.valueOf(value)); 
                                        }
                                        geschwindigkeit2 = value;
                                    }
                                }   

                            }


Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>