Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk5 min

How to Create Multiple Inputs in JOptionPane.showInputDialog()

Build a Java Swing dialog with several text fields and controls using a custom JPanel, showConfirmDialog(), safe validation, and reusable result handling.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

JOptionPane.showInputDialog() is designed for one logical input. For a form with several editable fields, place the controls on a custom JPanel and display it with JOptionPane.showConfirmDialog(). You can then detect OK, Cancel, and close actions and read each component after the modal dialog returns.

The recommended approach

There is no showInputDialog() overload that accepts several independent text fields. Its message argument is an Object, so a panel can technically be embedded, but the method still provides an input control and returns one value. showConfirmDialog() communicates a multi-field form more clearly: the panel is the content, and the return value tells you which option the user chose.

See the Oracle JOptionPane API for the available overloads, option constants, and return values.

Minimal working example

Create Swing components on the Event Dispatch Thread, retain references to them, and read them only after the dialog returns.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
TechGarden Wired Number Pad, USB Numeric Keypad 19 Key Number Keypad Keyboard for Laptop PC Computer Notebook, Big Print Letters - Black
  • Easy to Use - Our USB wired numpad does not require any driver or battery; easy to install, plug and play, gives you a stable connection.
  • Quiet & Soft Touch - Integrated ergonomic tilt provides comfortable typing, helps reduce the wrist strain. Low noise of the 19-key USB numeric keypad gives you a quiet and soft touch.
  • USB Wired Number Pad - Full-size 19mm keys improve speed and accuracy by making it easier to locate and press the numbers you are looking for. Numeric keypad supports NumLock.
  • Lightweight & Portable - The black numeric keypads are perfect for working on spreadsheet, you can works household, school, business trips, or daily use, very convenient number use.
  • Wide Compatibility - Compatible for Windows 2000, XP, Vista, or Windows 7/8/10, Android operating systems. Works with PC, desktop, notebook and other devices with USB ports.
import javax.swing.*;
import java.awt.*;

public class MultipleInputsExample {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JTextField nameField = new JTextField(20);
            JTextField emailField = new JTextField(20);
            JPasswordField passwordField = new JPasswordField(20);

            JPanel panel = new JPanel(new GridLayout(0, 2, 8, 8));
            panel.add(new JLabel("Name:"));
            panel.add(nameField);
            panel.add(new JLabel("Email:"));
            panel.add(emailField);
            panel.add(new JLabel("Password:"));
            panel.add(passwordField);

            int result = JOptionPane.showConfirmDialog(
                    null,
                    panel,
                    "Create Account",
                    JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.PLAIN_MESSAGE
            );

            if (result != JOptionPane.OK_OPTION) {
                return; // Cancel or a window-close action
            }

            String name = nameField.getText().trim();
            String email = emailField.getText().trim();
            char[] password = passwordField.getPassword();

            try {
                if (name.isEmpty() || email.isEmpty() || password.length == 0) {
                    JOptionPane.showMessageDialog(
                            null, "All fields are required.",
                            "Validation Error", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                System.out.println("Name: " + name);
                System.out.println("Email: " + email);
                System.out.println("Password length: " + password.length);
            } finally {
                java.util.Arrays.fill(password, '\0');
            }
        });
    }
}

The panel is passed as the dialog’s message. The original field objects remain available after the call, so their current contents can be retrieved directly. The dialog is modal: the calling code waits until the user completes or abandons it, while the Swing event system continues handling the interface.

Choosing a layout

Simple two-column forms

GridLayout(0, 2, 8, 8) is suitable when every row contains a label and a control. It automatically creates as many rows as needed.

More flexible forms

Use GridBagLayout when controls have different widths, optional rows, or explanatory text.

Rank #2
Sale
NOOX USB Numeric Keypad, Number Pad, 10 Key USB Keypad with Type C Adapter
  • ✔ Good Office Helper: Perfect for Laptops such as ChromeBook, VivoBook, HeroBook, IdeaPad and other computers without a numeric keypad, mini keyboard helps to enter numbers more conveniently and get your job done so much quicker
  • ✔ Wide Range of Applications: 10 key USB keypad digital number keyboard is plug and play, easy to use, suitable for home, office, school, accounting firm, Internet cafe and other places where you need to use laptops, notebooks, desktop computers, PC
  • ✔ 15 ° Tilt Design Numpad Keyboard: The ergonomic tilt design increases the comfort of use and helps reduce stress, ideal for those who deal with spreadsheets, accounting documents or financial applications
  • ✔ Compact Design: Mini size numeric keypad takes little space, very convenient to put in a bag or file bag. Silent key typing and comfort feeling, slip and fall proof base
  • ✔ Compatibility: Supports almost all operating systems. Works fine with Laptops, PC and desktop computers that have Windows 2000, XP, Me, Vista, or Windows 7/8/9/10/98/11 & mac OS X V10 6 operating systems.【NOTE: NOT fully compatible with mac OS system. Number keys part works fine, but the Function keys do not work】
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(4, 4, 4, 4);
c.anchor = GridBagConstraints.WEST;
c.fill = GridBagConstraints.HORIZONTAL;

c.gridx = 0; c.gridy = 0;
panel.add(new JLabel("First name:"), c);

c.gridx = 1; c.weightx = 1.0;
panel.add(new JTextField(20), c);

Avoid setBounds() and absolute positioning; fonts, look-and-feels, scaling, and localization can change component sizes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Using controls besides text fields

A custom panel can contain any Swing input component.

JComboBox<String> roleBox =
        new JComboBox<>(new String[] {"User", "Editor", "Admin"});
JCheckBox enabledBox = new JCheckBox("Account enabled", true);
JSpinner countSpinner =
        new JSpinner(new SpinnerNumberModel(1, 1, 100, 1));
JTextArea notesArea = new JTextArea(4, 20);

String role = (String) roleBox.getSelectedItem();
boolean enabled = enabledBox.isSelected();
int count = (Integer) countSpinner.getValue();
String notes = notesArea.getText().trim();

For one choice only, showInputDialog() can be appropriate:

Rank #3
Mechanical Numeric Keypad, 22-Key USB Numpad for Laptop with LED Backlight
  • MECHANICAL BLUE SWITCH - Professional blue switches mechanical numpad provides quick triggering, tactile feedback and audible click when a keystroke is registered. Perfect for typing, programming, and playing strategy games.(Warm Tips: not hotswap switch)
  • PLUG & PLAY - No drivers required, easy to use. Number keypad supports Num, ESC, Tab, Delete and a shortcut key which can quickly access to calculator to improve productivity.
  • BLUE BACKLIT - 3 backlight modes: full-lighting, breathing, lights-off turn on and off by ”Esc + Del”, bright and evenly distributed backlit keys, makes it easy to find the exactly keys when you are working in dimly lit rooms.
  • EXTREME DURABILITY - 10 key usb keypad with never faded ABS keycaps ensures 50 million times keystrokes. Gold-plated interface and magnet ring can to a large degree guarantees stable data transmitting
  • WIDELY COMPATIBILITY - Number pad for laptops and desktop computers works with Windows 2000/ XP/ Vista/ 7/ 8/ 10/ 11 operating systems. (Warm Tips: the keypad is not fully compatible with Macbook & Chromebook, the function keys do not work while the number keys part work fine)
Object selected = JOptionPane.showInputDialog(
        null, "Choose a role:", "Role",
        JOptionPane.QUESTION_MESSAGE, null,
        new String[] {"User", "Editor", "Admin"}, "User");

The selection-oriented overload returns one selected object; its presentation may be a combo box, list, or text field depending on the values and look-and-feel. See the full showInputDialog overload.

Validate input without losing typed values

Pressing OK does not make text valid. Parse and check values explicitly. To preserve entries after an error, create the components once and show the same panel again.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
JTextField nameField = new JTextField(20);
JTextField ageField = new JTextField(5);
JPanel panel = new JPanel(new GridLayout(0, 2, 8, 8));
panel.add(new JLabel("Name:"));
panel.add(nameField);
panel.add(new JLabel("Age:"));
panel.add(ageField);

while (true) {
    int result = JOptionPane.showConfirmDialog(
            null, panel, "User Details",
            JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.PLAIN_MESSAGE);

    if (result != JOptionPane.OK_OPTION) {
        break;
    }

    String name = nameField.getText().trim();
    String ageText = ageField.getText().trim();

    if (name.isEmpty()) {
        JOptionPane.showMessageDialog(null,
                "Name cannot be empty.",
                "Invalid Input", JOptionPane.ERROR_MESSAGE);
        continue;
    }

    try {
        int age = Integer.parseInt(ageText);
        if (age < 0 || age > 130) {
            throw new NumberFormatException();
        }
        System.out.println(name + ": " + age);
        break;
    } catch (NumberFormatException ex) {
        JOptionPane.showMessageDialog(null,
                "Enter an age from 0 to 130.",
                "Invalid Input", JOptionPane.ERROR_MESSAGE);
    }
}

Use Double.parseDouble() for decimal input rather than silently treating invalid text as zero. Treat every result other than OK_OPTION as an abandoned form; this covers the normal Cancel and window-close paths.

Rank #4
havit Bluetooth Number Pad Wireless Numeric Keypad Numpad 26 Keys Portable Mini Financial Accounting Rechargeable Numeric Pad for Windows Laptop Desktop, PC, Notebook (Black)
  • Widely Compatibility: This Bluetooth number pad is compatible with PC, laptop, desktop and computers running Windows systems. Note: This number pad does NOT support Mac OS systems
  • Multi-function 26-key Keypad: With NumLock, ESC, Delete and a shortcut key which can open the computer calculator directly etc.The number keyboard is more unique in that it can be combined into 3 currency symbols through Fn+composite keys
  • Bluetooth Number Pad Rechargeable: The wireless numeric keyboard with rechargeable lithium battery, avoid continuous battery consumption and battery replacement. This numeric keypad uses the latest stable buletooth 3.0 connection,plug and play, no delay and caton, fast data transmission, and working range is up to 33FT
  • Comfortable Numeric Pad: With quiet SCISSOR-SWITCH KEYS provides a comfortable and smooth typing experience, quick response and good tactile rebound, keep the office quiet and improve work efficiency.15° tilt design fits the human body habits, great for spreadsheets worker, accounting staff and financial officer
  • Long Using Time Keypad: The wireless numpad with a large capacity lithium battery, usually can use 1-2 months after fully charged (charged with the provided USB-A to USB-C cable). It will enter the sleep function after being idle for 1 hour, press any key to wake up

Returning a reusable form result

For application code, keep dialog construction and value extraction together and return a data object. Java records require a sufficiently modern Java release; use a regular class with fields and accessors in older projects.

import javax.swing.*;
import java.awt.*;

public class UserFormDialog {
    public static UserDetails show(Component parent) {
        JTextField nameField = new JTextField(20);
        JTextField emailField = new JTextField(20);

        JPanel panel = new JPanel(new GridLayout(0, 2, 8, 8));
        panel.add(new JLabel("Name:"));
        panel.add(nameField);
        panel.add(new JLabel("Email:"));
        panel.add(emailField);

        int result = JOptionPane.showConfirmDialog(
                parent, panel, "User Details",
                JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.PLAIN_MESSAGE);

        if (result != JOptionPane.OK_OPTION) {
            return null;
        }

        return new UserDetails(
                nameField.getText().trim(),
                emailField.getText().trim());
    }

    public record UserDetails(String name, String email) {}
}
UserFormDialog.UserDetails details = UserFormDialog.show(null);
if (details != null) {
    System.out.println(details.name());
    System.out.println(details.email());
}
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Can you still use showInputDialog()?

Yes, but it is usually confusing for a multi-field form.

JTextField firstField = new JTextField(15);
JTextField secondField = new JTextField(15);
JPanel panel = new JPanel(new GridLayout(0, 2));
panel.add(new JLabel("First:"));
panel.add(firstField);
panel.add(new JLabel("Second:"));
panel.add(secondField);

String returned = JOptionPane.showInputDialog(
        null, panel, "Multiple Inputs", JOptionPane.PLAIN_MESSAGE);

// Read firstField and secondField separately.

The returned String belongs to the input control associated with showInputDialog(); it does not combine the two custom fields. Use showConfirmDialog() when the panel itself is the form.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
Foloda Wireless Number Pads, Numeric Keypad Numpad 22 Keys Portable 2.4 GHz Financial Accounting Number Keyboard Extensions 10 Key for Laptop, PC, Desktop, Surface Pro, Notebook
  • 1.Number Pad for Laptop: Foloda number pad supports NumLock, ESC, Tab, Delete etc. With shortcut key which can open the computer calculator directly. The Multi - Function 10 keys USB keypad is a must - have laptop accessories. It's more unique than most keyboards, perfectly catering to the needs of laptop users who require efficient numeric input during work, study or financial accounting tasks.
  • 2.10 Key USB Keypad: Number Keypad is a great addition to your laptop accessories collection, is only 87g. As a key laptop accessory, Foloda numpad works by 2.4GHz wireless technology, with Plug and Play functionality. You can just plug the receiver into a USB port of your laptop. No device drivers needed, no delays and dropouts, ensuring fast data transmission. The maximum working range up to 32.8 ft. The Receiver is inserted in the battery compartment of the numeric keypad, making it convenient to carry around with your laptop.
  • 3.Wireless Number Pad: Number Pad is made of high quality ABS Material which offer great comfortable touch and precise control, good resilience fast response and reduce the press sound. It also has auto sleep function, lower power consumption, reflecting energy saving. Press any key to awake up the keypad. Power Supply by 2 x AAA Battery ( not included ). This makes it an excellent laptop accessories for use in quiet environments like libraries or offices, where noise - free operation is crucial.
  • 4.10 Key for Laptop: wireless usb number pad, an essential laptop accessory, works with PC, laptop and desktop computers that have Windows 2000 / XP / Vista / 7 / 8 / 10 systems. Whether you're using a Windows laptop for work or entertainment, Foloda usb numeric keypad is a reliable and compatible accessory.
  • 5.USB Number Pad for Laptop: Specialized in Home and try our best to offer the better product and customer service. If you have any question, feel free to contact with us. We are committed to ensuring that your experience with our laptop accessory - the wireless number pad - is nothing short of excellent.

When a custom JDialog is better

showConfirmDialog() is convenient for a small, modal form with standard buttons. Build a custom JDialog when you need:

  • Live validation while typing or an OK button that enables conditionally.
  • Custom button labels and detailed focus management.
  • A scroll pane, help area, tabs, or a large form.
  • Asynchronous work, specialized accessibility behavior, or fine-grained resizing.

The Oracle Swing dialog tutorial describes JOptionPane as a convenience API and explains when lower-level dialog construction is appropriate.

Common failure modes

  • Processing Cancel as OK: check the result before reading or saving values.
  • Assuming OK means valid: reject empty fields and catch numeric parsing exceptions.
  • Recreating the panel after every error: reuse the same components to retain typed values.
  • Expecting multiple automatic return values: read each component yourself.
  • Handling passwords as ordinary text: prefer getPassword(), avoid logging it, and clear the character array when finished. This does not guarantee that no copies exist.
  • Running in a server or CI process: graphical dialogs require a display and can throw HeadlessException in a headless environment.
  • Oversized forms: put the panel in a JScrollPane and provide a preferred size rather than forcing arbitrary option-pane dimensions.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.