如果你不需要太多的自定义行为的方式,JOptionPane是一个很好的时间保护。它负责确定/取消选项的放置和本地化,并且是一种快速而又脏的方式来显示自定义对话框,而不需要定义自己的类。大多数时候,JOptionPane中的“message”参数是一个String,但是您也可以传递JComponent或JComponent数组。
例:
JTextField firstName = new JTextField();
JTextField lastName = new JTextField();
JPasswordField password = new JPasswordField();
final JComponent[] inputs = new JComponent[] {
new JLabel("First"),
firstName,
new JLabel("Last"),
lastName,
new JLabel("Password"),
password
};
int result = JOptionPane.showConfirmDialog(null, inputs, "My custom dialog", JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
System.out.println("You entered " +
firstName.getText() + ", " +
lastName.getText() + ", " +
password.getText());
} else {
System.out.println("User canceled / closed the dialog, result = " + result);
}