无模式JDialog需要在父级之上可见

时间:2012-04-11 13:57:45

标签: java swing jdialog

我的应用程序提供了启动长时间运行任务的功能。发生这种情况时,会生成无模式JDialog,显示任务的进度。我特意使对话框无模式,允许用户在任务运行时与GUI的其余部分进行交互。

我面临的问题是,如果对话框隐藏在桌面上的其他窗口后面,则很难找到:任务栏上没有相应的项目(在Windows 7上),也没有可见的图标Alt + Tab菜单。

有解决这个问题的惯用方法吗?我曾考虑将WindowListener添加到应用程序的JFrame,并使用它将JDialog带到前台。然而,这可能会令人沮丧(因为可能这意味着JFrame会失去焦点)。

1 个答案:

答案 0 :(得分:8)

您可以创建非模态对话框并为其指定父框架/对话框。当您调出父框架/对话框时,它还会带来非模态对话框。

这样的事情说明了这一点:

public static void main(String[] args) throws IOException {
    JFrame frame = new JFrame();
    frame.setTitle("frame");
    JDialog dialog = new JDialog(frame, false);
    dialog.setTitle("dialog");
    final JButton button = new JButton("Click me");
    button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(button, "Hello");
        }
    });
    final JButton button2 = new JButton("Click me too");
    button2.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(button2, "Hello dialog");
        }
    });
    frame.add(button);
    dialog.add(button2);
    frame.pack();
    dialog.pack();
    frame.setVisible(true);
    dialog.setVisible(true);
}