When the user clicks a button, I want to show a popup form that should have at least two JTextFields and two JLabels, so using JOptionPane.showInputDialog
is not a possibility.
JDialog is a part Java swing package. The main purpose of the dialog is to add components to it. JDialog can be customized according to user need . Constructor of the class are: JDialog() : creates an empty dialog without any title or any specified owner.
Message dialogs are created with the JOptionPane. showMessageDialog() method. We call the static showMessageDialog() method of the JOptionPane class to create a message dialog.
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();
}
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With