Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 791
Adamski Avatar asked Apr 11 '12 13:04

Adamski


1 Answers

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);
}
like image 73
Guillaume Polet Avatar answered Sep 28 '22 18:09

Guillaume Polet