Java – JOptionPane with user input

A useful script to capture user input from JOptionPane:

String input = “”;

JTextField passwordField = new JTextField();

passwordField.setTransferHandler(null);

Object[] obj = {“Enter text”, passwordField};

Object stringArray[] = {“OK”, “Cancel”};

if (JOptionPane.showOptionDialog(null, obj, “Messdage with input”,
     JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, stringArray, obj) == JOptionPane.YES_OPTION) {

input = passwordField.getText();

      // TODO – USE INPUT VALUE
      System.out.println(input);
}else{
     //DO NOTHING – cancel or cross clicked
}

 

JO1

jo2

Output:

Hello World!

JAVA – JOptionPane Confirmation Dialog With YES / NO Options

This example shows how to use a JOptionPane confirmation dialog with YES / NO Options.

The response is stored in an integer variable which can be used later in the code to perform an action based on the user’s response.

You can change the button labels be changing the options [] values.

Object[] options = { “Yes”,
                            “No”};

int n =JOptionPane.showOptionDialog(null,
            “\n”
            + “Is today Monday?”
            + “\n\n”,
            “Please Confirm”,
            JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null,
            options,
            options[1]);

       // YES OPTION CLICKED
       if(n == 0){
           System.out.println(“YES Clicked”);
       }

       // NO OPTION CLICKED
       if(n == 1){
           System.out.println(“NO Clicked”);
       }

       // CROSS CLICKED
       if(n == -1){
           System.out.println(“Cross Clicked”);
       }