Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

Using getValue() will tell you how the dialog was closed. Since it's non-modal, you'll need to get that information once the dialog is closed, probably using a Thread that will wait that your dialog is closed to return the information. You don't give any details on what needs that information, so using another Thread might not be the best solution for you.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top