Java – preserve keyboard layout in swing applications?
•
Java
I have a Java Swing application that generates sub dialog boxes with text controls The problem is that when you change the keyboard layout in a sub dialog box, it changes immediately after closing the dialog box
What I need is to maintain the keyboard layout after switching, whether in the main frame or in the children's frame
This is an illustrative sscce:
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); } }
Solution
OK, I just solved this solution:
A listener of Java toolkit is added to the main () method, as shown below:
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 applies to all child dialogs generated using the parent window as constructor parameters In the closing event, the locale in the inputcontext of the child dialog box is placed in the inputcontext of its parent window
There may be some better ways
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码