Java Swing How to - Make JOptionPane handling ok, cancel and x button








Question

We would like to know how to make JOptionPane handling ok, cancel and x button.

Answer

import javax.swing.JFrame;
import javax.swing.JOptionPane;
/*from  ww w  .j  a v a  2s .  c om*/
public class Main {
  public static void main(String args[]) {
    int n = JOptionPane.showOptionDialog(new JFrame(), "Message", "Title",
        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
        new Object[] { "Yes", "No" }, JOptionPane.YES_OPTION);

    if (n == JOptionPane.YES_OPTION) {
      System.out.println("Yes");
    } else if (n == JOptionPane.NO_OPTION) {
      System.out.println("No");
    } else if (n == JOptionPane.CLOSED_OPTION) {
      System.out.println("Closed by hitting the cross");
    }
  }
}