How to Create a Simple Popup Form with Multiple Text Fields in Java
When implementing a desktop application, it is often necessary to collect user input through a form. While the JOptionPane.showInputDialog method can be used for simple input, it is not suitable for forms with multiple fields. This article provides an alternative solution that allows developers to create custom popup forms with multiple text fields.
To achieve this, developers should utilize the JOptionPane.showConfirmDialog method in conjunction with a custom panel containing the desired form components. The following steps outline the process:
The provided code sample demonstrates how to create a custom popup form with a JComboBox and two JTextField components:
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(); } }); } }
By leveraging this technique, developers can easily create custom popup forms with multiple fields, providing a more user-friendly and efficient way to collect user input within their Java applications.
The above is the detailed content of How to create a custom popup form with multiple text fields in Java?. For more information, please follow other related articles on the PHP Chinese website!