15

Have read old questions similar to this none of them helped my case.

OS: Windows 7 x64

Language Inputs:

enter image description here

I want to switch the language to Malayalam(India)[Google Input tools] for only one jTextField in Java Swing application and switch back to English(United States) for the rest of the fields.

UPDATE:

The field malyalamField is a javax.swing.JTextField

       javax.swing.JTextField malyalamField= new javax.swing.JTextField();
       malyalamField.setFont(new java.awt.Font("Arial Unicode MS", 0, 12));

Malayalam(India): A regional language used in the South Indian state named Kerala.

I tried to achieve that by firing the Alt + LShift key combo from java on the FocusGained and FocusGained events

int keyInput[] = { KeyEvent.VK_ALT, KeyEvent.VK_SHIFT};
Robot shiftkey=null;
Robot altkey=null;
try {
    shiftkey = new Robot();
    altkey=new Robot();
} catch (AWTException e) {
    e.printStackTrace();
}

altkey.keyPress(keyInput[0]);
shiftkey.keyPress(keyInput[1]);

altkey.keyRelease(keyInput[0]);
shiftkey.keyRelease(keyInput[1]);

(See bottom of post)

This works sometimes and sometimes it doesn't a little erratic behavior was observed. Sometimes it does not change back to English(United States) on FocusLost events even after the code getting executed.
enter image description here

I also tried using

         malyalamField.enableInputMethods(true);
         malyalamField.getInputContext().selectInputMethod(new Locale("MY", "IN"));

But this also did not work and selectInputMethod() returned NULL

I might be doing the selectInputMethod() with a wrong Locale

As of now the best I have is to fire the keystrokes from java.Is there a way this can be achieved?

SAMPLE CODE :

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

public class LanguageChangeForm extends javax.swing.JFrame {
    public LanguageChangeForm() {
        initComponents();
    }
    @SuppressWarnings("unchecked")
    private void initComponents() {

        englishField1 = new javax.swing.JTextField();
        malayalamFileld = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        englishField2 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        malayalamFileld.setFont(new java.awt.Font("Arial Unicode MS", 0, 11)); 
        malayalamFileld.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                malayalamFileldFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                malayalamFileldFocusLost(evt);
            }
        });

        jLabel1.setText("English Field");
        jLabel2.setText("Malayalam Field");
        jLabel3.setText("English Field");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(47, 47, 47)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(englishField2, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE)
                            .addComponent(englishField1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 49, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(malayalamFileld, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(34, 34, 34))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(49, 49, 49)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(englishField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(malayalamFileld, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(englishField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(152, Short.MAX_VALUE))
        );

        pack();
    }

    private void malayalamFileldFocusGained(java.awt.event.FocusEvent evt) {
        try{
        int keyInput[] = { KeyEvent.VK_ALT, KeyEvent.VK_SHIFT,,KeyEvent.VK_2};
        Robot robitkey=null;

        try {
            robitkey= new Robot();

        } catch (AWTException e) {

            e.printStackTrace();
        }
            robitkey.keyPress(keyInput[0]);
            robitkey.keyPress(keyInput[1]);
            robitkey.keyPress(keyInput[2]);
            robitkey.keyRelease(keyInput[0]);
            robitkey.keyRelease(keyInput[1]);
            robitkey.keyRelease(keyInput[2]);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    private void malayalamFileldFocusLost(java.awt.event.FocusEvent evt) {


        try{
        int keyInput[] = { KeyEvent.VK_ALT, KeyEvent.VK_SHIFT,,KeyEvent.VK_1};
        Robot robitkey=null;

        try {
            robitkey= new Robot();

        } catch (AWTException e) {

            e.printStackTrace();
        }
            robitkey.keyPress(keyInput[0]);
            robitkey.keyPress(keyInput[1]);
            robitkey.keyPress(keyInput[2]);
            robitkey.keyRelease(keyInput[0]);
            robitkey.keyRelease(keyInput[1]);
            robitkey.keyRelease(keyInput[2]);
        }catch(Exception e){
            e.printStackTrace();
        }

    }
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LanguageChangeForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LanguageChangeForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LanguageChangeForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LanguageChangeForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LanguageChangeForm().setVisible(true);
            }
        });
    }
    private javax.swing.JTextField englishField1;
    private javax.swing.JTextField englishField2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField malayalamFileld;

}
Sangeet Menon
  • 9,555
  • 8
  • 40
  • 58
  • 1
    What type is `malyalamField` please post an example from which we can reproduce easily. – Jean-François Savard Apr 07 '15 at 16:45
  • @Jean-FrançoisSavard have added the requested details about malayalamField – Sangeet Menon Apr 07 '15 at 16:53
  • @AndrewThompson, Have added a link of a sample code. – Sangeet Menon Apr 07 '15 at 17:30
  • Code should be posted here rather than at an external link.. – Andrew Thompson Apr 07 '15 at 17:47
  • @AndrewThompson I just didn't wanted the question to become too long – Sangeet Menon Apr 07 '15 at 18:20
  • 1
    *"didn't wanted the question to become too long"* I consider 'too long' to be when the site software approaches the point where it hits a char limit for posts. I experienced that on the [File Browser GUI](http://codereview.stackexchange.com/q/4446/7784) thread. That code was pushing **650 LOC.** ;) – Andrew Thompson Apr 07 '15 at 18:35
  • @AndrewThompson, Point noted Sir... – Sangeet Menon Apr 07 '15 at 18:51
  • I don’t know how the interaction of two distinct `Robot` instances is defined. Why are you creating two instances? By the way, Windows allows assigning unique key combos to each language/keyboard and using these is much more robust than using the one combo to cycle through the list (whose outcome depends on the previous state). – Holger Apr 10 '15 at 16:27
  • according to http://stackoverflow.com/questions/11926360/switching-from-french-to-arabic-in-jtextfields approach with `selectInputMethod()` should work. Try new `Locale("ml")`. Maybe you have a typo in your locale(you use `MY`). – Aliaksei Apr 13 '15 at 11:34
  • @Holger , I have tried both your suggestions **single instance** and **assigning unique key combos** (have updated my code). But, still not helping. – Sangeet Menon Apr 13 '15 at 11:41
  • 1
    Maybe the problem is that Windows 7 remembers the input language per application/window. So if your robot-generated switch key combo input interferes with an activation of another window, it may happen in that other window while your application remembers its old state which gets reactivated when reactivating its window. With Windows 8, there is per default a single, desktop wide input language so window activation events don’t matter anymore. – Holger Apr 13 '15 at 11:58

1 Answers1

3

This is locale you need:

Locale loc = new Locale("ml", "IN");
malayalamFileld.setLocale(loc);
malayalamFileld.getInputContext().selectInputMethod(loc);

But you need to know that this works only if user that started your program is Administrator/Root!!!

akuzmitski
  • 123
  • 11