Home  >  Article  >  Java  >  How to Create a Popup Form with Multiple Fields in Java Without JOptionPane.showInputDialog()?

How to Create a Popup Form with Multiple Fields in Java Without JOptionPane.showInputDialog()?

Barbara Streisand
Barbara StreisandOriginal
2024-11-07 08:26:03584browse

How to Create a Popup Form with Multiple Fields in Java Without JOptionPane.showInputDialog()?

Simple Popup Form with Multiple Fields

Question:

Is there a way to create a popup form with multiple fields without using JOptionPane.showInputDialog()?

Answer:

Consider Using JOptionPane Methods

While using JOptionPane methods may be initially dismissed due to the assumption that it's limited to one line of input, it offers options such as showInputDialog() and showMessageDialog() that can accommodate custom forms.

Alternative Approach

For a highly customized solution, consider the following code:

package gui;

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

/** @see https://stackoverflow.com/a/3002830/230513 */
class JOptionPaneTest {

    private static void display() {
        String[] items = {"One", "Two", "Three", "Four", "Five"};
        JComboBox<String> combo = new JComboBox<>(items);
        JTextField field1 = new JTextField("1234.56");
        JTextField field2 = new JTextField("9876.54");
        JPanel panel = new JPanel(new GridLayout(0, 1));
        panel.add(combo);
        panel.add(new JLabel("Field 1:"));
        panel.add(field1);
        panel.add(new JLabel("Field 2:"));
        panel.add(field2);
        int result = JOptionPane.showConfirmDialog(null, panel, "Test",
            JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        if (result == JOptionPane.OK_OPTION) {
            System.out.println(combo.getSelectedItem()
                + " " + field1.getText()
                + " " + field2.getText());
        } else {
            System.out.println("Cancelled");
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                display();
            }
        });
    }
}

Additional Considerations:

  • Customizing forms using JOptionPane hinges on the suitability of modality rather than the number of components.
  • Focus can be set to specific components by referencing Dialog Focus.

The above is the detailed content of How to Create a Popup Form with Multiple Fields in Java Without JOptionPane.showInputDialog()?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn