Pressing Yes/No on embedded JOptionPane has no effect

南楼画角 提交于 2019-12-11 07:54:45

问题


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.



来源:https://stackoverflow.com/questions/27339988/pressing-yes-no-on-embedded-joptionpane-has-no-effect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!