【发布时间】:2009-05-05 07:51:52
【问题描述】:
我想知道为什么我的 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();
}
}
如何避免主应用程序失去焦点? (不启用主框架)
【问题讨论】:
-
我不明白为什么您需要在单独的线程中打开对话框。最好在我说的 EDT 上做。
-
以上代码只是为了更好地理解和重现我的问题。我的真实应用程序在线程中执行了长时间运行的操作。