微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 在swing应用程序中保留键盘布局?

我有一个 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);
    }
}

解决方法

好的,我刚刚解决了这个解决方案:

在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);

它适用于使用父窗口生成的所有子对话框作为构造函数参数.在关闭事件中,子对话框的InputContext中的Locale被放入其父窗口的InputContext中.

可能有一些更好的方法.

原文地址:https://www.jb51.cc/java/128461.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐