Youcef Laidani Youcef Laidani - 3 months ago 11
Java Question

Characters of Barcode scanner not display correctly

I try to use bar code scanner to read a bar code from products, but I get special characters like this:

incorrect

After searching I found a solution: I changed the language of writing to English, so I get a correct value like this:

language

correct

My question is, is there any way to change the language of writing with Java code automatically, to not force the user to change the language every time?

Or at least is there any way to make an action with keyboard automatically like

Ctrl + Shift


Thank you.

Answer

You can use this code:

codeBare.addFocusListener(new java.awt.event.FocusAdapter() {
    public void focusLost(java.awt.event.FocusEvent e) {
        changeLanguageCodeBare(false);
    }

    public void focusGained(java.awt.event.FocusEvent e) {
        changeLanguageCodeBare(true);
    }
});

The code of method changeLanguageCodeBare is:

private void changeLanguageCodeBare(boolean isChangeLanguage) {
        if (isChangeLanguage) {
            codeBare.getInputContext().selectInputMethod(new Locale("en", "US"));
            boolean isOn = Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
            if (!isOn) {
                try {
                    Robot robot = new Robot();
                    robot.keyPress(KeyEvent.VK_CAPS_LOCK);
                    robot.keyRelease(KeyEvent.VK_CAPS_LOCK);
                } catch (AWTException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        } else {
            codeBare.getInputContext().selectInputMethod(new Locale("xx", "XX"));
            try {
                Robot robot = new Robot();
                robot.keyPress(KeyEvent.VK_CAPS_LOCK);
                robot.keyRelease(KeyEvent.VK_CAPS_LOCK);
            } catch (AWTException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }

knowing that : codeBare is the name of JTextField

NB :

  1. Do not forget to add the English language in your language preferences (PC)
  2. Change the order of your language preferences as needed.