Search code examples
javaswingjoptionpane

How to use JOptionPane with many options? java


I was experimenting with different JOptionPane and I came across having different options in a array and then using it on JOptionPane. However I am finding it hard to use the given options, so for example, how would I use my GO back option?

  String[] options = new String[] {"Go ahead", "Go back", "Go forward", "close me"};
      int option =  JOptionPane.showOptionDialog(null, "Title", "Message", 
            JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
            null, options, options[0]);

I have tried doing it like this but it won't work

    if (option == JOptionPane.options[1]){

    }

edit:

 switch(option){
          case 1: System.out.println("1");
              break;
          case 2: System.out.println("2");
              break;
          case 3: System.out.println("3");
              break;
          case 4: System.out.println("4");
              break;
          }

Solution

  • Why not simply

    String[] options = new String[] {"Go ahead", "Go back", "Go forward", "close me"};
    int option =  JOptionPane.showOptionDialog(null, "Title", "Message", 
          JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
          null, options, options[0]);
    
    if (option != JOptionPane.CLOSED_OPTION) {
      System.out.println(options[option]);
    } else {
      System.out.println("No option selected".);
    }
    

    Note that use of an enum for the options will more easily allow use of the state or command design pattern. For example:

    import javax.swing.JOptionPane;
    
    public class OptionPaneEgWithEnums {
       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) {
             // user closed the JOptionPane without selecting
          } else {
             State state = State.values()[option];
             doAction(state);
             // 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;
       }
    }