0

I made ​​a method to input numbers. But I want that input is numeric but a dot (.) Can still be entered. please my friend help me. Thanks

private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {                                     
    // TODO add your handling code here:
    FilterHanyaAngka(evt);
}

public void FilterHanyaAngka(java.awt.event.KeyEvent evt) {
    char c = evt.getKeyChar();
    if (!((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
            evt.consume();
    }
}

3 Answers 3

1

Don't use KeyListener to filter content to the a text component, you have no idea of knowing in what order the KeyListeners will be notified and the key stroke may already have being sent to the field before you.

Instead you should use a DocumentFilter

Take a look at Text Component Features, in particular Implementing a Document Filter and here for examples

In fact, I believe there is actually a numeric filter example listed there...

Sign up to request clarification or add additional context in comments.

Comments

0

You can use ASCII instead of the Character or KeyEvent class. Look at this:

public class ASCIITest {

public static void main(String[] args) {
    char c = '3';

    if ((c >= '0' && c <= '9') || c == '.') {
        //some code..
    }
}

}

For more information read about the ASCII chart

Comments

0

yes I've found the solution in my opinion

public void filterDesimal(java.awt.event.KeyEvent evt) {
    char ch = evt.getKeyChar();
    if (!((ch == '.') ||
            (ch ==  '0') ||
            (ch ==  '1') ||
            (ch ==  '2') ||
            (ch ==  '3') ||
            (ch ==  '4') ||
            (ch ==  '5')||
            (ch ==  '6') ||
            (ch ==  '7') ||
            (ch ==  '8') ||
            (ch ==  '9') ||
            (ch ==  ',') ||
            (ch ==  KeyEvent.VK_BACK_SPACE) ||
            (ch ==  KeyEvent.VK_DELETE)
            )){
        evt.consume();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.