1

I'm trying to add an exit confirmation check to JFrame but I want the dialog to be undecorated. I've figured I need to use custom JDialog and custom JOptionPane.

frame.addWindowListener(new java.awt.event.WindowAdapter() {

        @Override
        public void windowClosing(java.awt.event.WindowEvent windowEvent) {
            JDialog dialog = new JDialog();
            dialog.setUndecorated(true);


            JOptionPane pane = new JOptionPane("Are you sure that you want to exit?",
             JOptionPane.QUESTION_MESSAGE,JOptionPane.YES_NO_OPTION);


            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); //I don't even know if this line does anything


            dialog.setContentPane(pane);
            dialog.pack();
            dialog.setLocationRelativeTo(frame);
            dialog.setVisible(true);

            System.out.println("Next Line"); //this line does not work.

        }
    }); 

The dialog appears exactly as I wanted but clicking yes or no does nothing. Dialog does not disappear and I couldn't find a way to check which button is clicked. "Next Line" is never printed to console .

Adam
  • 35,919
  • 9
  • 100
  • 137
WVrock
  • 1,725
  • 3
  • 22
  • 30

2 Answers2

2

Read the section from the Swing tutorial on How to Make Dialogs for working examples of using a JOptionPane.

If you really want to add a JOptionPane to your own JDialog, then read the JOptionPane API for a basic example of how to check which button was selected.

camickr
  • 321,443
  • 19
  • 166
  • 288
2

Embedding JOptionPane on its own isn't enough. You need to register a callback for the Yes and No button presses and handle them appropriately. This can be done by overriding the setValue() method

JOptionPane pane = new JOptionPane(
        "Are you sure that you want to exit?",
        JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION) {
     @Override
        public void setValue(Object newValue) {
         if (newValue == Integer.valueOf(JOptionPane.YES_OPTION)) {
             System.out.println("yes");
         } else if ( newValue == Integer.valueOf(JOptionPane.NO_OPTION)) {
             System.out.println("no");

         }
     }
};
Adam
  • 35,919
  • 9
  • 100
  • 137
  • This works. Thanks. I have another question. Instead of writing things to console I've made no to close the dialog. Is this the preferable way or there is a built-in way to close it? – WVrock Dec 07 '14 at 05:56
  • 1
    To the best of my knowledge JOptionPane when embedded can't automatically close its hosting frame, how would it know? – Adam Dec 07 '14 at 06:03