简体   繁体   中英

Modeless JDialog needs to be visible on top of parent

My application offers the ability to launch a long-running task. When this occurs a modeless JDialog is spawned showing the progress of the task. I specifically make the dialog modeless to allow the user to interact with the rest of the GUI whilst the task runs.

The problem I'm facing is that if the dialog becomes hidden behind other windows on the desktop it becomes difficult to locate: There is no corresponding item on the task bar (on Windows 7), nor is there an icon visible under the Alt+Tab menu.

Is there an idiomatic way to solve this problem? I had considered adding a WindowListener to the application's JFrame and use this to bring the JDialog to the foreground. However, this is likely to become frustrating (as presumably it will mean the JFrame then loses focus).

You can create a non-modal dialog and give it a parent frame/dialog. When you bring up the parent frame/dialog, it also brings the non-modal dialog.

Something like this illustrates this:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM