Search code examples
javajoptionpane

JOptionPane with multiple inputs


I need to get input in different ways using JOptionPane. Specifically, I need a dropdown menu along with the default input text field to both be present in the same JOptionPane. Is this achievable? if so, how?


Solution

  • If you need different components in your pane, you can try to implement something like this:

    JTextField firstName = new JTextField();
    JTextField lastName = new JTextField();
    JPasswordField password = new JPasswordField();
    final JComponent[] inputs = new JComponent[] {
            new JLabel("First"),
            firstName,
            new JLabel("Last"),
            lastName,
            new JLabel("Password"),
            password
    };
    int result = JOptionPane.showConfirmDialog(null, inputs, "My custom dialog", JOptionPane.PLAIN_MESSAGE);
    if (result == JOptionPane.OK_OPTION) {
        System.out.println("You entered " +
                firstName.getText() + ", " +
                lastName.getText() + ", " +
                password.getText());
    } else {
        System.out.println("User canceled / closed the dialog, result = " + result);
    }