我想知道为什么我的 JDialog 将我的主应用程序插入后台。这意味着如果将显示 JDialog 并且用户单击“确定”或“取消”,主应用程序将失去其焦点并将被插入后台。
经过我的调查,我发现只有当我在显示 JDialog 时禁用我的主框架时才会发生此行为。
可以使用以下代码重现此行为:
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;<p></p>
<p>import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;</p>
<p>public class FocusTest {</p>
<pre><code>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();
}
</code></pre>
<p>}
</p>
如何避免主应用程序失去焦点? (不启用主框架)
最佳答案
您可以为 JDialog 类设置以下选项
//setUndecorated(true);
setFocusableWindowState(false);
setFocusable(false);
为此,您可以创建自己的 JDialog 类。您只需从 JDialog 扩展并将代码放入 Constructor 调用中。
关于java - JDialog 让主应用程序失去焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/823795/