javaswingjoptionpanejdialognon-modal

JOptionpane + JDialog (non-modal) get the return value


I have a non-modal dialog with two input text fields shown with the JOptionPane with OK and CANCEL buttons. I show the dialog as below.

        JTextField field_1 = new JTextField("Field 1");
        JTextField field_2 = new JTextField("Field 2");

        Object[] inputField = new Object[] { "Input 1", field_1,
                "Input_2", field_2 };

        JOptionPane optionPane = new JOptionPane(inputField,
                JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
        JDialog dialog = optionPane.createDialog(null, "Input Dialog");
        dialog.setModal(false);
        dialog.setVisible(true);

How can i get the return value from the dialog? Means i need to get whether Ok or CANCEL button is pressed. How can achieve this?


Solution

  • One way would be to add a ComponentListener to the dialog and listen for its visibility to change,

    dialog.addComponentListener(new ComponentListener() {
        @Override
        public void componentResized(ComponentEvent e) { }
    
        @Override
        public void componentMoved(ComponentEvent e) { }
    
        @Override
        public void componentShown(ComponentEvent e) { }
    
        @Override
        public void componentHidden(ComponentEvent e) {
            if ((int) optionPane.getValue()
                    == JOptionPane.YES_OPTION) {
                // do YES stuff...
            } else if ((int) optionPane.getValue()
                    == JOptionPane.CANCEL_OPTION) {
                // do CANCEL stuff...
            } else {
                throw new IllegalStateException(
                        "Unexpected Option");
            }
        }
    });
    

    Note: you should probably use the ComponentAdapter instead; I'm showing the whole interface for illustration.