Main Tutorials

Java Swing – Keep dialog window up

The most common (and simple) way to implement a dialog in our application is the JOptionPane class. In this article we will discuss how to “overwrite” the default behaviour of JOptionPane that closes the dialog window when the user clicks a JOptionPane-created button.

What we need to know before we move on to the examples is that when we use a JOptionPane in our application what really runs behind the scenes is a modal JDialog. JOptionPane is a container that automatically creates a JDialog and adds itself to it’s content pane.

1. Basic Example

In this example we stop the dialog window from closing automatically and instead handle it on our own by implementing a PropertyChange listener. The example below is the absolute basis of implementing this mechanic in your code since there’s no handling of user interaction or input checking.

KeepDialogUp.java

package com.mkyong.stayup;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class KeepDialogUp {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        ImageIcon icon = new ImageIcon("src/images/turtle64.png");

        Object[] options = {"I DO LOVE TURTLES"};
        JOptionPane jop = new JOptionPane("Admit your love for turtles\nor you shall not pass!!"
                , JOptionPane.ERROR_MESSAGE, 0, icon, options, options[0]);

        JDialog dialog = new JDialog(frame, "You LOVE turtles", true);
        dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        dialog.setContentPane(jop);

        jop.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if (JOptionPane.VALUE_PROPERTY.equals(evt.getPropertyName())) {
                    dialog.dispose();
                    JOptionPane.showMessageDialog(null, "Good for you >:P");
                    System.exit(0);
                }

            }
        });
        dialog.pack();
        dialog.setLocationRelativeTo(frame);
        dialog.setVisible(true);
    }
}

Output:

swing-keep-dialog-up-1

If the user tries to close the window, nothing happens. If the user clicks the “I DO LOVE TURTLES” button the program shows the following dialog and then exits.

swing-keep-dialog-up-2

2. Example with Listeners

Now let’s spice up the previous example. We will add a windowListener to handle user’s attempt to close the dialog and we will check the user’s input in propertyChangeListener.

KeepDialogUpExtended.java

package com.mkyong.stayup;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class KeepDialogUpExtended {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        ImageIcon icon = new ImageIcon("src/images/turtle64.png");

        Object[] options = {"I DO LOVE TURTLES"};
        JOptionPane jop = new JOptionPane("Admit your love for turtles\nor you shall not pass!!",
                JOptionPane.ERROR_MESSAGE, 0, icon, options, options[0]);

        JDialog dialog = new JDialog(frame, "You LOVE turtles", true);
        dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        dialog.setContentPane(jop);

        dialog.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent evt) {
                JOptionPane.showMessageDialog(frame, "YOU SHALL NOT PASS", "!!",
                        JOptionPane.ERROR_MESSAGE);
            }
        });

        jop.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if (JOptionPane.VALUE_PROPERTY.equals(evt.getPropertyName())) {
                    if (jop.getValue().equals(options[0])) {
                        dialog.dispose();
                        JOptionPane.showMessageDialog(null, "Good for you >:P");
                        System.exit(0);
                    } else {
                        JOptionPane.showMessageDialog(frame, "There is no\n>> ESC <<",
                                "You little shenanigan...", JOptionPane.ERROR_MESSAGE);
                    }
                }

            }
        });
        dialog.pack();
        dialog.setLocationRelativeTo(frame);
        dialog.setVisible(true);
    }

}

Output:

swing-keep-dialog-up-1

If the user tries to close the window:

swing-keep-dialog-up-3

If the user presses the Esc button:

swing-keep-dialog-up-4

This pretty much sums up this mechanic. Some might argue that handling user input the traditional way where we would check the return value of the JOptionPane is more efficient in resources. Maybe or maybe not; depending on the rest of the code this mechanic might be the missing piece. What is certain though is that the more you know the higher the chance you will make the right choice.

References

  1. Stopping Automatic Dialog Closing
  2. Class Dialog – Java 8 API
  3. Class JOptionPane – Java 8 API

About Author

author image
Marilena Panagiotidou is a senior at University of the Aegean, in the department of Information and Communication Systems Engineering. She is passionate about programming in a wide range of languages. You can contact her at [email protected] or through her LinkedIn.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments