Accept only numbers and a dot in Java TextField
NickName:Agustín Ask DateTime:2013-08-06T23:14:24

Accept only numbers and a dot in Java TextField

I've got one textField where I only accept numbers from the keyboard, but now I have to change it as it's a "price textField" and I would also need to accept a dot "." for any kind of prices.

How can I change this in order to get what I need?

ptoMinimoField = new JTextField();
        ptoMinimoField.setBounds(348, 177, 167, 20);
        contentPanel.add(ptoMinimoField);
        ptoMinimoField.setColumns(10);
        ptoMinimoField.addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
                char caracter = e.getKeyChar();
                if (((caracter < '0') || (caracter > '9'))
                        && (caracter != '\b')) {
                    e.consume();
                }
            }
        });

Copyright Notice:Content Author:「Agustín」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/18084104/accept-only-numbers-and-a-dot-in-java-textfield

Answers
Vũ Trung Sơn 2015-04-16T18:50:38

Enter the double number of JTextField in java\n\nprivate boolean dot = false;\nprivate void txtMarkKeyTyped(java.awt.event.KeyEvent evt) { \n char vChar = evt.getKeyChar();\n if (txtMark.getText().equals(\"\"))\n dot = false;\n if (dot == false){\n if (vChar == '.') dot = true;\n else if (!(Character.isDigit(vChar)\n || (vChar == KeyEvent.VK_BACK_SPACE)\n || (vChar == KeyEvent.VK_DELETE))) {\n evt.consume();\n }\n } else {\n if (!(Character.isDigit(vChar)\n || (vChar == KeyEvent.VK_BACK_SPACE)\n || (vChar == KeyEvent.VK_DELETE))) {\n evt.consume();\n }\n }\n}\n",


Qwerky 2013-08-06T15:18:20

This bit of code;\n\nif (((caracter < '0') || (caracter > '9'))\n && (caracter != '\\b')) {\n\n\ndecides whether to consume the key event. You need to update the condition so it doesn't consume the dot character.",


SchneiderJinn 2019-04-15T04:48:14

Just right click on TextField / events / key / keytyped\n\nif(!Character.isDigit(evt.getKeyChar())){\n evt.consume();}\n",


Alireza Ravandi 2015-08-26T04:46:31

/////////////\n\n JTextField ptoMinimoField = new JTextField();\n ptoMinimoField.addKeyListener(new KeyAdapter() {\n public void keyTyped(KeyEvent e) {\n boolean ret = true;\n try {\n\n Double.parseDouble(ptoMinimoField.getText()+e.getKeyChar());\n }catch (NumberFormatException ee) {\n ret = false;\n }\n\n\n if (!ret) {\n e.consume();\n }\n }\n });\n",


irbef 2016-08-16T08:09:51

maybe can help you for filtering keytyped just number and dot\n\npublic void filterHanyaAngkaDot(java.awt.event.KeyEvent evt){\n char c = evt.getKeyChar();\n if (! ((Character.isDigit(c) ||\n (c == KeyEvent.VK_BACK_SPACE) ||\n (c == KeyEvent.VK_DELETE))\n )&& c==KeyEvent.VK_COMMA\n )\n {\n evt.consume();\n }\n }\n",


Suresh Atta 2013-08-06T15:16:35

As suggested by Oracle ,Use Formatted Text Fields \n\n\n Formatted text fields provide a way for developers to specify the valid set of characters that can be typed in a text field. \n\n\namountFormat = NumberFormat.getNumberInstance();\n...\namountField = new JFormattedTextField(amountFormat);\namountField.setValue(new Double(amount));\namountField.setColumns(10);\namountField.addPropertyChangeListener(\"value\", this);\n",


kulakesh 2017-06-01T10:07:40

JTextField txtMyTextField = new JTextField();\n\nnumOnly(txtMyTextField);\n\npublic void numOnly(Object objSource){\n ((Component) objSource).addKeyListener(new KeyListener() {\n\n @Override\n public void keyTyped(KeyEvent e) {\n String filterStr = \"0123456789.\";\n char c = (char)e.getKeyChar();\n if(filterStr.indexOf(c)<0){\n e.consume();\n }\n }\n @Override\n public void keyReleased(KeyEvent e) {}\n\n @Override\n public void keyPressed(KeyEvent e) {}\n });\n}\n\n\n\n WARNING: This function does not follow proper java documentation\n guide.\n",


Brayan Byrdsong 2014-09-06T09:23:51

I just use a try-catch block: \n\ntry {// if is number\n Integer.parseInt(String);\n} catch (NumberFormatException e) {\n // else then do blah\n}\n",


Abdellah Benhammou 2013-12-01T15:38:26

I have been using this solution, it's simple and efficient:\n\n jtextfield.addKeyListener(new KeyAdapter() {\n public void keyTyped(KeyEvent e) {\n char vChar = e.getKeyChar();\n if (!(Character.isDigit(vChar)\n || (vChar == KeyEvent.VK_BACK_SPACE)\n || (vChar == KeyEvent.VK_DELETE))) {\n e.consume();\n }\n }\n });\n",


Wender 2015-04-21T12:19:31

JTextField txField = new DoubleJTextField();\n\nCreate a file DoubleJTextField.java and be happy\n\npublic class DoubleJTextField extends JTextField {\n public DoubleJTextField(){\n addKeyListener(new KeyAdapter() {\n public void keyTyped(KeyEvent e) {\n char ch = e.getKeyChar();\n\n if (!isNumber(ch) && !isValidSignal(ch) && !validatePoint(ch) && ch != '\\b') {\n e.consume();\n }\n }\n });\n\n }\n\n private boolean isNumber(char ch){\n return ch >= '0' && ch <= '9';\n }\n\n private boolean isValidSignal(char ch){\n if( (getText() == null || \"\".equals(getText().trim()) ) && ch == '-'){\n return true;\n }\n\n return false;\n }\n\n private boolean validatePoint(char ch){\n if(ch != '.'){\n return false;\n }\n\n if(getText() == null || \"\".equals(getText().trim())){\n setText(\"0.\");\n return false;\n }else if(\"-\".equals(getText())){\n setText(\"-0.\");\n }\n\n return true;\n }\n}\n",


Noiwong Suwijak 2018-02-15T09:05:25

private boolean point = false;\nprivate void txtProductCostPriceAddKeyTyped(java.awt.event.KeyEvent evt) \n{\n char Char = evt.getKeyChar();\n if (txtProductCostPriceAdd.getText().equals(\"\"))\n point = false;\n if (point == false){\n if (Char == '.') point = true;\n else if (!(Character.isDigit(Char) || (Char == KeyEvent.VK_BACK_SPACE) || (Char == KeyEvent.VK_DELETE))) {\n evt.consume();\n }\n } else {\n if (!(Character.isDigit(Char) || (Char == KeyEvent.VK_BACK_SPACE) || (Char == KeyEvent.VK_DELETE))) {\n evt.consume();\n }\n }\n}\n",


MiguelMunoz 2016-11-21T01:56:37

Don't ever use a KeyListener for this. Your code above has two serious bugs, both caused by the use of a KeyListener. First, it will miss any text that gets pasted in. Whenever I find a field that filters out non-digits, I always try to paste in some text, just for fun. Nine times out of ten, the text gets accepted, because they used a key listener. \n\nSecond, you didn't filter out modifiers. If the user tries to save their work by typing control-s while they're in this field, your key listener will consume the event. And if your application assigns, say, a control-5 or alt-5 shortcut to some action, this KeyListener will add a 5 to the field when they type it, even though the user wasn't trying to type a character. You did figure out that you needed to pass the backspace key, but that's not all you need to pass. Your arrow keys won't work. Neither will your function keys. You can fix all these problems, but it starts to be a lot of work.\n\nThere's a third disadvantage, but it only shows up if you adapt your application to a foreign alphabet, particularly one that takes multiple keystrokes to generate a single character, like Chinese. These alphabets make KeyListeners useless.\n\nThe trouble is this. You need to filter characters, but KeyListeners aren't about characters, they're about keystrokes, which are not the same thing: Not all keystrokes generate characters, and not all characters are generated by keystrokes. You need an approach that looks at characters after they've been generated, and after modified keystrokes have already been filtered out.\n\nThe simplest approach is to use a JFormattedTextField, but I've never liked that approach, because it doesn't format or filter as you type. So instead, I will use a DocumentFilter. DocumentFilters don't operate on keystrokes, they operate on the text strings as they get inserted to your JTextField's data model. Hence, all the control-keys, arrow and function keys and such don't even reach the DocumentFilter. All pasted text goes through the DocumentFilter, too. And, for languages that take three keystrokes to generate a single character, the DocumentFilter doesn't get invoked until the character is generated. Here's what it looks like:\n\n ptoMinimoField = new JTextField();\n ptoMinimoField.setBounds(348, 177, 167, 20); // Don't do this! See below.\n contentPanel.add(ptoMinimoField);\n ptoMinimoField.setColumns(10);\n\n PlainDocument document = (PlainDocument) ptoMinimoField.getDocument();\n document.setDocumentFilter(new DigitFilter());\n}\n\n\nThe DigitFilter class looks like this:\n\npublic class DigitFilter extends DocumentFilter {\n @Override\n public void insertString(FilterBypass fb, int offset, String text, \n AttributeSet attr) throws BadLocationException {\n super.insertString(fb, offset, revise(text), attr);\n }\n\n @Override\n public void replace(FilterBypass fb, int offset, int length, String text,\n AttributeSet attrs) throws BadLocationException {\n super.replace(fb, offset, length, revise(text), attrs);\n }\n\n private String revise(String text) {\n StringBuilder builder = new StringBuilder(text);\n int index = 0;\n while (index < builder.length()) {\n if (accept(builder.charAt(index))) {\n index++;\n } else {\n // Don't increment index here, or you'll skip the next character!\n builder.deleteCharAt(index);\n }\n }\n return builder.toString();\n }\n\n /**\n * Determine if the character should remain in the String. You may\n * override this to get any matching criteria you want. \n * @param c The character in question\n * @return true if it's valid, false if it should be removed.\n */\n public boolean accept(final char c) {\n return Character.isDigit(c) || c == '.';\n }\n}\n\n\nYou could write this as an inner class, but I created a separate class so you can override the accept() method to use any criteria you want. You may also notice that I don't test for digits by writing this:\n\n(c < '0') || (c > '9')\n\n\nInstead, I do this:\n\nCharacter.isDigit()\n\n\nThis is faster, cleaner, and works with foreign numbering systems. I also don't need your test for the backspace character, '\\b'. I'm guessing that your first KeyListener was filtering out the backspace key, which was your first clue that it was the wrong approach.\n\nAnd on an unrelated note, don't hard code your component positions. Learn how to use the LayoutManagers. They're easy to use, and they'll make your code much easier to maintain.",


arcy 2013-08-06T15:16:23

Have you looked at a JFormattedTextField? It would seem it does what you want.",


More about “Accept only numbers and a dot in Java TextField” related questions

Accept only numbers and a dot in Java TextField

I've got one textField where I only accept numbers from the keyboard, but now I have to change it as it's a "price textField" and I would also need to accept a dot "." for any kind of prices. How ...

Show Detail

Accept only numbers and a dot in Java TextField

I've got one textField where I only accept numbers from the keyboard, but now I have to change it as it's a "price textField" and I would also need to accept a dot "." for any kind of prices. How ...

Show Detail

jTextField accept only one dot in java calculator?

I have created a simple calculator in java using net beans. In this calculator when user accidentally press dot button(jButton) multiple time textfield shows many dots as user pressed. for example if

Show Detail

JTextField accept only numbers and one dot

I want that my text field accept only numbers (digit) and one dot, because it is a field in which the user can write the price of products. I have this code but it doesn't work well, it only accept

Show Detail

regular expression to accept only integers and decimal numbers

Iam working with ext js.I have a textfield that should accept either an integer or a decimal number. Iam using regular expression to implement that. But its not working. Here is my code... {...

Show Detail

Grails: How do I make a g:textfield to accept only numbers or only letters?

I have different g:textfields throughout my code, and I want to make some of the to only accept numbers or letters, but I don't want to validate for them, I want them to be immediate, like if the

Show Detail

TextField that accepts only positive numbers - JavaFX

I'm trying to create a TextField in JavaFX (using Scene Builder) that accepts only positive numbers. I'm trying actually to make a TextField for a 'Credit Card Number' which accepts 13 - 16 numeric

Show Detail

make TextField accept only numbers and + sign in flutter

I want the field to allow the entry of numbers and the + sign only but all I could do was make the field allow the entry of numbers only and I couldn't make it accept the + sign here is my code Tex...

Show Detail

How to create TextField that only accepts numbers

I'm new to SwiftUI and iOS, and I'm trying to create an input field that will only accept numbers. TextField("Total number of people", text: $numOfPeople) The TextField currently allows alphabetic

Show Detail

I want to only accept the A to Z in my textfield . And do not accept the numbers in swift 5

i created a username textfield and i want my textfield do not accept the numbers in swift 5 i tried this bud didnt work func OnlyCharacter(_ textField: UITextField, shouldChangeCharactersIn ran...

Show Detail