Search code examples
javaswingjoptionpanejdialog

Pressing Yes/No on embedded JOptionPane has no effect


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 .


Solution

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