ygg*_*raa 7 java swing keyboard-layout
我有一个Java Swing应用程序,它生成带有文本控件的子对话框.问题是,当您在子对话框中更改键盘布局时,它会在关闭对话框后立即更改.
我需要的是无论是在主框架还是在儿童框架中切换,在切换后都要保持的键盘布局.
这是一个说明问题的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);
}
}
Run Code Online (Sandbox Code Playgroud)
好吧,我刚刚解决了这个解决方案:
在 main() 方法中向 java 工具包添加了一个侦听器,如下所示:
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);
Run Code Online (Sandbox Code Playgroud)
它适用于使用父窗口作为构造函数参数生成的所有子对话框。在关闭事件时,子对话框的 InputContext 中的 Locale 被放入其父窗口的 InputContext 中。
也许有更好的方法。
| 归档时间: |
|
| 查看次数: |
2368 次 |
| 最近记录: |