-1

I have a problem with actionListener (keyPressed) on TextField. That's the method which is called after key is pressed but it doesn't change character in TextField:

private void checkIfTypingDots(java.awt.event.KeyEvent kev) {
            int keyCode = kev.getKeyCode();
            if(keyCode == KeyEvent.VK_COMMA) {
                kev.setKeyCode(KeyEvent.VK_PERIOD);
            }
    }

How can I dynamically change comma to dot in TextField by event - keyPressed?

Michu93
  • 5,058
  • 7
  • 47
  • 80
  • 1
    IMO you'd do better using a `DocumentListener` for this – ControlAltDel Jan 20 '17 at 14:27
  • I doubt you can change the key code of the event being fired. Why should you do that instead of asking the user to type the correct thing anyways? If you really want to support that you probably should replace the character right at the time of adding it to the text or replace commas with dots afterwards (might be easier but probably slower if the text is large). – Thomas Jan 20 '17 at 14:28
  • @Thomas it's production application and many people works on this. Sometimes they type comma, sometimes dot. It's my duty to make it user friendly – Michu93 Jan 20 '17 at 14:29
  • Maybe just use getText() method to assing it to String and then string.replace(',', '.'), afterwards setText() to put replaced string to the textField – DanoPlu Jan 20 '17 at 14:33
  • @DanoPlurana I think using replace is not the best solution. If there is a method keyPressed() then my example seems like textbook example – Michu93 Jan 20 '17 at 14:36
  • 1
    @ControlAltDel You're be better off using a `DocumentFilter` which is notified before the document is mutated, where a `DocumentListener` is notified while it's been mutated, causing exceptions to be thrown if you try and change it :P – MadProgrammer Jan 20 '17 at 21:38

1 Answers1

0

Dynamically change comma to dot in key event (swing)

Use a DocumentFilter to translate the string before it is entered into the Document.

Read the section from the Swing tutorial on How to Implement a DocumentFilter for more information to get you started.

To override the replace(...) method you might do something like:

public void replace(final FilterBypass fb, final int offs, final int length, final String str, final AttributeSet a)
{
    if (str.equals(","))
        super.replace(fb, ofs, length, ".", a);
    else
        super.replace(fb, offs, length, str, a);
}
camickr
  • 321,443
  • 19
  • 166
  • 288