Simple popup java form with at least two fields
You should at least consider one of the JOptionPane
methods such as showInputDialog()
or showMessageDialog()
.
Addendum: The choice to use JOptionPane
hinges more on the suitability of modality, rather than on the number of components shown. See also How to Make Dialogs.
Addendum: As noted in a comment by @camickr, you can set the focus to a particular component using the approach discussed in Dialog Focus, cited here.
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();
}
});
}
}
With the small UiBooster library you can build a form dialog in a few lines of code.
FilledForm form = new UiBooster()
.createForm("Personal informations")
.addText("Whats your first name?")
.addTextArea("Tell me something about you")
.addSelection(
"Whats your favorite movie?",
Arrays.asList("Pulp Fiction", "Bambi", "The Godfather", "Hangover"))
.show();