JDialog 让主应用程序失去焦点 [英] JDialog lets main application lose focus

查看:40
本文介绍了JDialog 让主应用程序失去焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么我的 JDialog 将我的主应用程序推入后台.这意味着如果将显示 JDialog 并且用户单击确定"或取消",主应用程序将失去焦点并将被推入后台.

I wonder why my JDialog pushes my main application into background. That means if the JDialog will be shown and the user clicks "OK" or "CANCEL" the main application looses its focus and will be pushed into the background.

经过我的调查发现,只有在显示 JDialog 时禁用主框架才会发生这种行为.

After my investigation I found out, that this behaviour only happens if I disable my main frame for the time I show the JDialog.

可以使用以下代码重现此行为:

This behaviour could be reproduced with the following code:


import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

导入 javax.swing.JButton;导入 javax.swing.JDialog;导入 javax.swing.JFrame;导入 javax.swing.JOptionPane;

import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JOptionPane;

公共类 FocusTest {

public class FocusTest {

private JFrame frame;

public FocusTest() {
    frame = new JFrame();
    frame.setSize(200,200);
    JButton btn = new JButton("Open Dialog");
    btn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            callDialog(null, "title", "message");
        }
    });
    frame.add(btn);
    frame.setVisible(true);
}

private void callDialog(Component parent, String title, String message) {
    frame.setEnabled(false);
    Thread t1 = new Thread(new Runnable() {
        public void run() {
            JOptionPane optionPane = new JOptionPane("",
                    JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
                JDialog dialog = optionPane.createDialog(null, "");
                dialog.setVisible(true);
                frame.setEnabled(true);
        }
    });
    t1.start();
}

public static void main(String[] args) {
    new FocusTest();
}

}

如何避免主应用程序失去焦点?(不启用主框架)

How can I avoid that the main application looses its focus? (without enabling the main frame)

推荐答案

您可以为 JDialog 类设置以下选项

You can set the following options to an JDialog class

//setUndecorated(true);
setFocusableWindowState(false);
setFocusable(false);

为此,您可以创建自己的 JDialog 类.您只需从 JDialog 扩展并将代码放入构造函数调用中即可.

For this you can ceate your own JDialog class. You only have to extend from JDialog and put the code into the Constructor call.

这篇关于JDialog 让主应用程序失去焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆