javaswingjoptionpane

How to get a string from input box?


How can I get a string from the user by using input box with JOptionPane method in Java? I know how to get int but I can't get String from user.


Solution

  • It is quite straight forward. See below minimal example.

    When user enters some text in the text field and clicks "OK" button, showInputDialog() method returns that text entered by the user. If user clicks "Cancel" button, null is returned.

    import javax.swing.JOptionPane;
    
    public class InputDialog
    {
      public static void main(String[] args)
      {
        String userInput = JOptionPane.showInputDialog(null, "What is your name?", "Input", JOptionPane.QUESTION_MESSAGE);
        System.out.println("User input: " + userInput);
      }
    }