7

I'd like to change the windows keyboard that is currently being used programatically.

I'm writing a dictionary program for an eastern language, and I want it to switch to another keyboard when the user clicks in a different table column.

I looked into this and found example using Windows PowerShell, and native C++ code. The PowerShell did not seem to work and I'm not familiar with the native Windows API and C. Any help on how to actually get this done in Java would be greatly appreciated.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
JavaMonkey22
  • 861
  • 11
  • 20
  • This might be of some interest to you [**Add API for changing the current Keyboard Layout (?) programmatically**](http://www.java.net/node/643787). As far as I understood it, they are saying, it cannot be done :-) (easily) That's why, +1 for the question :-) – nIcE cOw Jan 24 '13 at 13:02
  • Thanks for the link, but this seems to be from 2004, and still no solution to this problem ? – JavaMonkey22 Jan 24 '13 at 13:18

2 Answers2

7

Here's a blog post that explains how to do it: change input method
In a nutshell:

yourMainJFrame.getInputContext().selectInputMethod(new Locale("fa", "IR")); 
vitalii
  • 3,335
  • 14
  • 18
  • Thanks, looks great for Swing but I'm using JavaFx 2.2 and I can't seem to find the equivalent?! is there one ? – JavaMonkey22 Jan 24 '13 at 17:43
  • I tried this solution, and failed on Ubuntu) setxkbmap programm kinda works for me, but then i'm unable to choose switch layout from unity. Looks like very platform-specific question.Using jni in Windows is not that hard here's good explanation from stackoverflow: http://stackoverflow.com/a/2389473/1573825 there are two functions in user32.dll - GetKeyboardLayoutName and LoadKeyboardLayout – vitalii Jan 25 '13 at 14:47
  • eto pravilni otvet – CodeToLife Feb 03 '20 at 13:32
0

Above method doesn't work for me, so i used primitive way using Robot

public static void switchKeyboardLanguage()
{
    SwingUtilities.invokeLater(new Runnable()
    {
        public void run()
        {
            try
            {
                Robot robot = new Robot();
                robot.keyPress(KeyEvent.VK_ALT);
                robot.keyPress(KeyEvent.VK_SHIFT);
                robot.delay(10);
                robot.keyRelease(KeyEvent.VK_ALT);
                robot.keyRelease(KeyEvent.VK_SHIFT);
            }
            catch (AWTException e)
            {
                LogUtils.logError("Failed to use Robot, got exception: ", e);
            }
        }
    });
}
Adir Dayan
  • 1,308
  • 13
  • 21