I am working on a Java application for people learning German, and I have a problem with special characters in this language. I want to create a subclass of JTextField that will interpret ALT + a as ä, ALT + o as ö, etc., At the same time, as usual, for all ASCII characters.
My attempts:
public class GermanTextField extends JTextField implements KeyListener{ public GermanTextField() { init(); }
The code above does not work ( GermanTextField behaves like a standard JTextField), and when I print evt.getKeyChar() for the console, this is what I get:
? ? ? ?
This may be due to my own language, because ALT + o produces - on my system. Of course, I could do it like this:
public void keyTyped(KeyEvent evt) { if(evt.getKeyChar() == 'ó'){ setText(getText() + "ö"); evt.consume(); } }
But it probably will not work on any systems other than Polish.
My question is: is there any solution to this problem that will behave as expected on systems with different language settings?
A complete solution to this problem based on MvGs answer:
package daswort.gui; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.HashMap; import java.util.Map; import javax.swing.JTextField; public class GermanTextField extends JTextField implements KeyListener{ private Map<Integer, String> transform = new HashMap<Integer, String>(); public GermanTextField() { init(); } public GermanTextField(int columns) { super(columns); init(); } public GermanTextField(String text, int columns) { super(text, columns); init(); } public GermanTextField(String text) { super(text); init(); } private void init() { transform.put(KeyEvent.VK_A, "äÄ"); transform.put(KeyEvent.VK_U, "üÜ"); transform.put(KeyEvent.VK_O, "öÖ"); addKeyListener(this); } public void keyPressed(KeyEvent evt) { if(evt.isAltGraphDown()){ String umlaut = transform.get(evt.getKeyCode()); if(umlaut != null){ int idx = evt.isShiftDown() ? 1 : 0; setText(getText() + umlaut.charAt(idx)); } } } public void keyReleased(KeyEvent arg0) {} public void keyTyped(KeyEvent evt) { if(evt.isAltGraphDown()){ evt.consume(); } } }
source share