Java Swing How to - Use JOptionPane with many options








Question

We would like to know how to use JOptionPane with many options.

Answer

import javax.swing.JOptionPane;
// www .j a  va 2 s. c  o m
public class Main {
   public static void main(String[] args) {
      int option = JOptionPane.showOptionDialog(null, "Title", "Message",
            JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null,
            State.values(), State.values()[0]);
      if (option == JOptionPane.CLOSED_OPTION) {
         System.out.println("user closed the JOptionPane without selecting"); 
      } else {
         State state = State.values()[option];
         doAction(state);
         System.out.println("code to do something based selected state"); 
      }
   }

   private static void doAction(State state) {
      System.out.println("The user has selected to " + state);
   }
}

enum State {
   AHEAD("Go Ahead"), BACK("Go Back"), FORWARD("Go Forward"), CLOSE("Close Me");
   private State(String text) {
      this.text = text;
   }

   private String text;

   public String getText() {
      return text;
   }

   @Override
   public String toString() {
      return text;
   }
}