I want to remap the decimal comma (German keyboard) to a point for certain JTextField
s. I have experimented with getInputMap()
and getActionMap
, but so far nothing worked. Best result I got so far was that the comma didn't work at all.
I think there should be some way using the input map, but how?
Below is a small example program, could someone give me a hint as to what to fill in at the location of the comment? Or is this completely wrong anyway?
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
public class KeyTest extends JFrame {
private JTextField textField;
public KeyTest() {
textField = new JTextField();
add(textField);
InputMap map = textField.getInputMap();
map.put(KeyStroke.getKeyStroke(','), /* what to do here? */);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
KeyTest test = new KeyTest();
test.pack();
test.setVisible(true);
}
});
}
}
EDIT:
Perhaps I was not clear enough with my question. There is no problem with normal numbers. I'm just looking to make user input more convenient when entering dates. these are in the format "DD.MM.YYYY"
in Germany. That means, you cannot enter dates using just the numeric keypad because we do not have a decimal point, but a comma. That's why I want to replace comma with point in the textfields used for entering dates.
All the input fields for plain text and numbers already work fine, and even the date inputs work. I just want to make typing easier. Just yesterday I noticed a similar functionality in Libreoffice, where the comma on the numeric keypad (I have a German keyboard) gets replaced automatically in numerical cells (My locale is set to English), but only in cells containing numerical values. This also happens as you type.
Use the following
textField.addKeyListener(new KeyListener(){
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (c== ',')
e.setKeyChar('.');
}
});