如何使用JOptionPane有很多选项? java的

时间:2014-02-22 17:25:20

标签: java swing joptionpane

我正在尝试使用不同的JOptionPane,我在数组中遇到了不同的选项,然后在JOptionPane上使用它。但是我发现很难使用给定​​的选项,例如,我如何使用我的GO返回选项?

  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.options[1]){

    }

编辑:

 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;
          }

2 个答案:

答案 0 :(得分:3)

为什么不简单

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".);
}

请注意,对选项使用枚举将更容易使用状态或命令设计模式。例如:

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;
   }
}

答案 1 :(得分:2)

    Just see option is of int type. Hence JOptionPane.showOptionDialog(null, "Title", "Message", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,null, options, options[0]) is returning an integer value. 

You may use it as:

     if (option == 0) {
                  System.out.println("Go Ahead");
              } else if ( option == 1) {
                  System.out.println("Go back");
              } else if (option == 2 ) {
                  System.out.println("Go forward");
              } else if (option == 3) {
                  System.out.println("close me");
              }