8

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).

Lynn Crumbling
  • 12,985
  • 8
  • 57
  • 95
Adamski
  • 54,009
  • 15
  • 113
  • 152
  • Why don't you use a JFrame instead? That is one of main differences: the button in the taskbar. – Martijn Courteaux Apr 11 '12 at 14:01
  • Because I don't want the dialog to offer maximise or minimise functionality. – Adamski Apr 11 '12 at 14:07
  • You can use setResizable(false); I would allow minimising, otherwise, the application might be a bit offensive, IMO. – Martijn Courteaux Apr 11 '12 at 14:13
  • Do you pass a parent frame/dialog to that progress dialog? If so, then bringing the parent to the front should also bring the dialog (and by setting modal to false, the user can still access the rest of your GUI) – Guillaume Polet Apr 11 '12 at 14:15

1 Answers1

8

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);
}
Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
  • Thanks - that worked a treat. Looks like I was setting the dialog's location relative to a parent component but not actually constructing the JDialog with an owner. – Adamski Apr 11 '12 at 16:22