Preserving keyboard layout in swing app?
Asked Answered
V

3

8

I have a Java Swing application wich spawns child dialogs with text controls. And the problem is that when you change keyboard layout in child dialog, it changes back right after the dialog is closed.

What I need is the keboard layout to stay after being switched whether it was switched in the main frame or in a child frame.

Here is a SSCCE that illustrates the problem:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class InheritInputContext {

    public static void main(String[] arg) {
        final MainFrame mainFrame = new MainFrame();
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                mainFrame.setPreferredSize(new Dimension(300, 400));
                mainFrame.pack();
                mainFrame.setLocationRelativeTo(null);
                mainFrame.setVisible(true);
            }
        });

    }
}


class MainFrame extends JFrame {

    MainFrame() {
        setLayout(new BorderLayout());
        JTextArea textArea = new JTextArea();
        add(textArea, BorderLayout.CENTER);

        JButton dialogBtn = new JButton("Dialog");
        add(dialogBtn, BorderLayout.SOUTH);
        dialogBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ChildDialog cd = new ChildDialog(MainFrame.this);
                cd.setPreferredSize(new Dimension(200, 200));
                cd.setLocationRelativeTo(MainFrame.this);
                cd.pack();
                cd.setVisible(true);
            }
        });
    }
}


class ChildDialog extends JDialog {

    ChildDialog(Window w) {
        super(w);
        JTextArea textArea = new JTextArea();
        getContentPane().add(textArea);
    }
}
Vomer answered 12/3, 2012 at 13:30 Comment(1)
Are you talking about the keyboard layout of the operating system? A little confused over here.Deciduous
V
3

Ok, I just settled with this solution:

Added a listener to java toolkit in main() method like this:

AWTEventListener awtWindowListener = new AWTEventListener() {
    @Override
    public void eventDispatched(AWTEvent event) {
        if (event instanceof WindowEvent) {
            if (WindowEvent.WINDOW_CLOSED == event.getID()
                    || WindowEvent.WINDOW_CLOSING == event.getID()) {
                Window child = ((WindowEvent) event).getWindow();
                Window parent = SwingUtilities.getWindowAncestor(child);
                if (parent == null) return;
                InputContext childIC = child.getInputContext();
                parent.getInputContext().selectInputMethod(childIC.getLocale());
            }
        }

    }
};

Toolkit.getDefaultToolkit().addAWTEventListener(awtWindowListener, AWTEvent.WINDOW_EVENT_MASK);

It works on all child dialogs generated with parent window as constructor parameter. On close event Locale from InputContext of child dialog is put into InputContext of it's parent window.

May be there is some better way though.

Vomer answered 13/3, 2012 at 7:30 Comment(0)
M
1

Are you just looking for a way to have any layout change affect your application globally?

If so, one approach is to create a custom listener, have the various components that care about the layout change register their interest in such events, and then fire off a change layout event that triggers the change in all components when it's changes in any one of them.

Another way to do it would be store the layout properties in an object that's accessible to any of the components, and have them update their layout periodically via a timer. This would be less desirable, however, because there would probably be lots of needless updates vs. the "only update on event" mode of operation. I'm guessing users of your application won't be changing their keyboard layout more than once or twice per session (as opposed to every 5 seconds)?

Another, third way, to do this is to have the keyboard layout settings stored at the application level, and loaded at startup. Then, when a keyboard layout change happens, prompt the user to restart the app for the changes to take effect globally.

Morbidity answered 12/3, 2012 at 14:20 Comment(5)
Yes, i am looking for a way to preserve any layout change made in application, to avoid the need to change layout over and over again in each new dialog. Right now i am exploring option of using AWTEventListener on app level, to avoid writing additional code for every child frameVomer
The on-timer update is out of question, it would be overload. Asking for app-reload is out of question too, user needs to change between 2 languages all the time.Vomer
I looked in NetBeans and IntellijIdea too, there is the same thing. You open Settings, for example, change input language, close Settings and the keyboard layout returns to what it used to be before. In other applications (browsers, mssql, notepad) the change of keyboard layout is consistant all over the app.Vomer
Sounds like triggering an app-wide event might be the best route for your needs.Morbidity
I added an AwtListener for WindowEvent which on CLOSING event changes a parent window's InputContext to that as of it's closing child dialog. Will post code snippet as soon as SOF allows me :)Vomer
D
1

Yes and no: yggdraa's code of Mar 13 worked fine on Windows but failed on Linux.

There may be no universal solution for Linux at all: no such things as Windows' GetKeyboardLayout() and ActivateKeyboardLayout() there. Some configuration-dependent hacks might be possible though, such as parsing the output of xset (details here) and forcing the layout, say, on key up/down.

In the example above, the input selection code in eventDispatched() gets called too late - when the OS keyboard has already switched back to the system-default US.

A few brute force attempts didn't work either: myParticularJField.setLocale(myForcedLocale) from the field's focus handler gets immediately undone upon the first key press. Same for forcing the top-level (JFrame/JDialog) Locale.

Update:

We have only Windows in production, so making this work under Linux is impractical: too much effort.

Just in case, a byproduct. This correctly determines which layout is currently active: default or alternative ("local"). It can't distinguish among several alternative layouts:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class LinuxKeyboardLayoutStatus {

    public enum LayoutType { DEFAULT, LOCAL }

    public LinuxKeyboardLayoutStatus.LayoutType getCurrentKeyboardLayoutType() throws IOException, InterruptedException {
        String[] command = createCommand();
        Process p = Runtime.getRuntime().exec(command);
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String l = r.readLine();
        r.close();
        p.waitFor();
        return decodeLayoutType(l);
    }

    protected String[] createCommand() {
        return new String[] { "/bin/sh", "-c", "xset -q | grep LED | awk '{ print $10 }' | cut -c5" };
    }

    protected LinuxKeyboardLayoutStatus.LayoutType decodeLayoutType(String commandOutput) {
        return
            commandOutput != null && !commandOutput.equals("0") ? LayoutType.LOCAL : LayoutType.DEFAULT;
    }

}

Update:

In Ubuntu, the change back to the default layout happens at the X window level (DBus events). A workaround: to turn off separate layouts for each window: Settings => Keyboard => Layouts, uncheck "Separate layout for each window."

Danonorwegian answered 13/9, 2012 at 10:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.