Pressing Yes/No on embedded JOptionPane has no eff

2019-08-07 03:09发布

问题:

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 .

回答1:

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

         }
     }
};


回答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.