68

Is there a way to create multiple input in JOptionPane.showInputDialog instead of just one input?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
siaooo
  • 1,827
  • 3
  • 23
  • 25

2 Answers2

146

Yes. You know that you can put any Object into the Object parameter of most JOptionPane.showXXX methods, and often that Object happens to be a JPanel.

In your situation, perhaps you could use a JPanel that has several JTextFields in it:

import javax.swing.*;

public class JOptionPaneMultiInput {
   public static void main(String[] args) {
      JTextField xField = new JTextField(5);
      JTextField yField = new JTextField(5);

      JPanel myPanel = new JPanel();
      myPanel.add(new JLabel("x:"));
      myPanel.add(xField);
      myPanel.add(Box.createHorizontalStrut(15)); // a spacer
      myPanel.add(new JLabel("y:"));
      myPanel.add(yField);

      int result = JOptionPane.showConfirmDialog(null, myPanel, 
               "Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
      if (result == JOptionPane.OK_OPTION) {
         System.out.println("x value: " + xField.getText());
         System.out.println("y value: " + yField.getText());
      }
   }
}
APerson
  • 8,140
  • 8
  • 35
  • 49
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 8
    +1, and I'll throw in a link to Dialog Focus (http://tips4java.wordpress.com/2010/03/14/dialog-focus/) which includes a simple class to set focus on a text field that you might find helpful. – camickr Jul 02 '11 at 15:32
  • 1
    @Marco: Please have a look at the [Swing Tutorials](http://download.oracle.com/javase/tutorial/uiswing/components/index.html) and in particular the section on [JPanels](http://download.oracle.com/javase/tutorial/uiswing/components/panel.html) – Hovercraft Full Of Eels Jul 04 '11 at 10:07
  • 1
    How can i add the label one below another? I created a vertical strut but didt't work. Nice solution btw. – Kostas Thanasis Mar 24 '20 at 15:54
  • 2
    @KostasThanasis: use the right layout manager for the JPanel holding the JLabels. A `new GridLayout(0, 1)` could work, the `0, 1` standing for variable number of rows `0`, and 1 column, `1`. – Hovercraft Full Of Eels Mar 24 '20 at 17:38
38

this is my solution

JTextField username = new JTextField();
JTextField password = new JPasswordField();
Object[] message = {
    "Username:", username,
    "Password:", password
};

int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
    if (username.getText().equals("h") && password.getText().equals("h")) {
        System.out.println("Login successful");
    } else {
        System.out.println("login failed");
    }
} else {
    System.out.println("Login canceled");
}
smidhonza
  • 493
  • 4
  • 8