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:
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!