Search code examples
javaswingjoptionpane

how to capture ok button pressed from JOptionPane


I want to capture the ok button event when the "OK" button is pressed in on a JOptionPane. I then want to display a jframe. I've found numerous tutorials and videos on capturing all sorts of events except for the JOptionPane. The Java docs are not much help for a newbie. Hoping someone can help. I have the following.

JOptionPane.showMessageDialog(frame,
            "Press OK to get a frame");

How do I implement the listener to capture the OK pressed event.

private class Listener implements ActionListener {

    public void
      actionPerformed(ActionEvent e) {

    }

}

Solution

  • There's no need to capture it -- code flow will return immediately post the JOptionPane display line. If you want to know if OK vs cancel vs delete the window was pressed, then use a different JOptionPane -- use the JOptionPane.showConfirmDialog(...), and capture the result returned from this method call.

        String text = "Press OK to get a frame";
        String title = "Show Frame";
        int optionType = JOptionPane.OK_CANCEL_OPTION;
        int result = JOptionPane.showConfirmDialog(null, text, title, optionType);
        if (result == JOptionPane.OK_OPTION) {
            //...
        }