Preserving keyboard layout in a JTextfield?

跟風遠走 提交于 2019-12-09 07:03:00

问题


Simple example: 2 JTextFields, one for a spanish word another one for it's translation. Is there a way to preserve keyboard layout per JTextField so that the user wouldn't have to switch back and forth?

TIA.


回答1:


Yes, this demo code uses the keyboard layout for the selected locales in each text field:

public class InputMethodTest {

  public static void main(String[] args) {
    final InputContext en = InputContext.getInstance();
    en.selectInputMethod(Locale.UK);
    final InputContext es = InputContext.getInstance();
    es.selectInputMethod(new Locale("es", "ES"));
    JTextArea english = new JTextArea() {
      @Override
      public InputContext getInputContext() {
        return en;
      }
    };
    JTextArea spanish = new JTextArea() {
      @Override
      public InputContext getInputContext() {
        return es;
      }
    };

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(new GridLayout());
    frame.getContentPane().add(new JScrollPane(english));
    frame.getContentPane().add(new JScrollPane(spanish));
    frame.setSize(600, 400);
    frame.setVisible(true);
  }
}

Tested on Windows XP Home with EN and ES keyboard layouts installed (via Control Panel > Regional and Language Options > Languages > Details...). See the Java Input Method Framework for more details.




回答2:


No, keyboard layouts are managed by the OS or desktop environment.




回答3:


If you know exactly the layout of the Spanish keyboard in question you could theoretically process KeyEvents yourself, translating them into the appropriate character. However this would not be an easy thing to do. You would probably end up inserting characters into the textfields yourself.



来源:https://stackoverflow.com/questions/834758/preserving-keyboard-layout-in-a-jtextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!