我想知道为什么我的 JDialog 将我的主应用程序推入后台。这意味着,如果显示 JDialog 并且用户单击“确定”或“取消”,则主应用程序将失去焦点并将被推入后台。
经过调查,我发现,只有当我在显示 JDialog 时禁用主框架时,才会发生这种行为。
可以使用以下代码重现此行为:
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;
公共类焦点测试{
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();
}
}
您可以为 JDialog 类设置以下选项
//setUndecorated(true);
setFocusableWindowState(false);
setFocusable(false);
为此,您可以创建自己的 JDialog 类。您只需从 JDialog 扩展并将代码放入构造函数调用中即可。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)