Java - 如何创建自定义对话框?

2022-01-24 00:00:00 java swing jframe joptionpane jdialog

我在 JFrame 上有一个按钮,单击该按钮时我希望弹出一个对话框,其中包含多个文本区域供用户输入.我一直在四处寻找,试图弄清楚如何做到这一点,但我越来越困惑.有人可以帮忙吗?

I have a button on a JFrame that when clicked I want a dialog box to popup with multiple text areas for user input. I have been looking all around to try to figure out how to do this but I keep on getting more confused. Can anyone help?

推荐答案

如果您不需要太多的自定义行为方式,JOptionPane 是一个很好的节省时间的方法.它负责 OK/Cancel 选项的放置和本地化,并且是一种快速而简单的方式来显示自定义对话框,而无需定义您自己的类.大多数情况下,JOptionPane 中的消息"参数是一个字符串,但您也可以传入一个 JComponent 或 JComponent 数组.

If you don't need much in the way of custom behavior, JOptionPane is a good time saver. It takes care of the placement and localization of OK / Cancel options, and is a quick-and-dirty way to show a custom dialog without needing to define your own classes. Most of the time the "message" parameter in JOptionPane is a String, but you can pass in a JComponent or array of JComponents as well.

例子:

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);
}

相关文章