JDialog 让主应用程序失去焦点

fla*_*ash 2 java swing

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

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

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


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

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

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();
}
Run Code Online (Sandbox Code Playgroud)

}

Run Code Online (Sandbox Code Playgroud)

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

Mar*_*erg 5

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

//setUndecorated(true);
setFocusableWindowState(false);
setFocusable(false);
Run Code Online (Sandbox Code Playgroud)

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