I am currently working on a GUI and I want to display a pop up window identical to the one shown below using JOptionPane. I am currently able to display the JTextField and JLabe
You can use the JOptionPane.showOptionDialog method.
@param message the
Object
to display
The message
parameter can be a simple string or a complex object like a JPanel.
For the layout of your panel, we can use a layout manager called GridBagLayout.
For more information, check the following guide: How To Use GridBagLayout
Here's a quick example of everything together:
public static void main(String[] args) {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets = new Insets(8, 8, 8, 8);
JLabel label;
label = new JLabel("Student Name");
constraints.gridx = 0;
constraints.gridy = 0;
panel.add(label, constraints);
JTextField studentNameField = new JTextField(20);
constraints.gridx = 1;
constraints.gridy = 0;
panel.add(studentNameField, constraints);
label = new JLabel("Departament");
constraints.gridx = 0;
constraints.gridy = 1;
panel.add(label, constraints);
JTextField departamentField = new JTextField(20);
constraints.gridx = 1;
constraints.gridy = 1;
panel.add(departamentField, constraints);
label = new JLabel("Course");
constraints.gridx = 0;
constraints.gridy = 2;
panel.add(label, constraints);
JTextField courseField = new JTextField(20);
constraints.gridx = 1;
constraints.gridy = 2;
panel.add(courseField, constraints);
Object[] options = {"OK", "CANCEL"};
int result = JOptionPane.showOptionDialog(null, panel, null, JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (result == 0) {
String studentName = studentNameField.getText();
String departament = departamentField.getText();
String course = courseField.getText();
System.out.println(studentName);
System.out.println(departament);
System.out.println(course);
}
}