如何制作对话框

原文: https://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html

对话窗口是一个独立的子窗口,用于在主 Swing 应用程序窗口之外进行临时通知。大多数对话框向用户显示错误消息或警告,但对话框可以显示图像,目录树或与管理它们的主 Swing 应用程序兼容的任何内容。

为方便起见,几个 Swing 组件类可以直接实例化并显示对话框。要创建简单的标准对话框,请使用 JOptionPane 类。 ProgressMonitor 类可以显示一个对话框,显示操作的进度。另外两个类别 JColorChooserJFileChooser 也提供标准对话框。要打开打印对话框,您可以使用 Printing API。要创建自定义对话框,请直接使用 JDialog 类。

简单对话框的代码可以是最小的。例如,这是一个信息对话框:

An informational dialog requires minimal code

以下是创建和显示它的代码:

  1. JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.");

本节的其余部分包括以下主题:

每个对话框都依赖于 Frame 组件。当该帧被销毁时,其依赖对话框也被销毁。当帧被图标化时,其相关的对话框也会从屏幕上消失。当帧被去图标化时,其相关的对话框返回到屏幕。 swing JDialog 类从 AWT Dialog类继承此行为。

对话框可以是模态。当模态对话框可见时,它会阻止用户输入程序中的所有其他窗口。 JOptionPane 创建模态的JDialog。要创建非模态对话框,必须直接使用JDialog类。

从 JDK 7 开始,您可以使用新的 Modality API 修改对话框窗口模态行为。有关详细信息,请参阅新模态 API

JDialog类是 AWT java.awt.Dialog 类的子类。它添加了根窗格容器,并支持对Dialog对象的默认关闭操作。这些与JFrame具有的功能相同,直接使用JDialog与使用JFrame非常相似。如果您要直接使用JDialog,那么您应该了解使用顶级容器如何制作帧,特别是响应窗口的材料 - 结束活动

即使使用JOptionPane实现对话框,您仍然在后台使用JDialog。原因是JOptionPane只是一个可以自动创建JDialog并将其自身添加到JDialog内容窗格的容器。

这是显示对话框的应用程序的图片。

DialogDemo lets you bring up many kinds of dialogs


Try this::

  1. Click the Launch button to run the Dialog Demo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.Launches the DialogDemo example

  2. 单击显示它!按钮。 将出现一个模态对话框。在您关闭它之前,应用程序将无法响应,但必要时它将自行重新绘制。您可以通过单击对话框中的按钮或显式关闭对话框,例如使用对话框窗口装饰。

  3. 在“更多对话框”窗格中,单击底部单选按钮,然后单击“显示”!按钮。 将出现非模态对话框。请注意,当非模态对话框启动时,DialogDemo 窗口仍然完全正常工作。
  4. 显示非模态对话框时,图标化 DialogDemo 窗口。 对话框将从屏幕上消失,直到您对 DialogDemo 窗口进行 deiconify。

使用JOptionPane,您可以快速创建和自定义几种不同类型的对话框。 JOptionPane支持布局标准对话框,提供图标,指定对话框标题和文本以及自定义按钮文本。其他功能允许您自定义对话框显示的组件并指定对话框在屏幕上的显示位置。您甚至可以指定选项窗格将自身置于内部框架JInternalFrame)而不是JDialog

创建JOptionPane时,特定于外观的代码会将组件添加到JOptionPane并确定这些组件的布局。

JOptionPane的图标支持可让您轻松指定对话框显示的图标。您可以使用自定义图标,根本不使用图标,也可以使用四个标准JOptionPane图标中的任何一个(问题,信息,警告和错误)。每个外观都有自己的四个标准图标版本。下图显示了 Java(和 Windows)外观中使用的图标。

Icons used by JOptionPane | 图标说明 | Java 的外观和感觉 | Windows 的外观和感觉 | | —- | —- | —- | | 题 | The Java look and feel icon for dialogs that ask questions | The Windows look and feel icon for dialogs that ask questions | | 信息 | The Java look and feel icon for informational dialogs | The Windows look and feel icon for informational dialogs | | 警告 | The Java look and feel icon for warning dialogs | The Windows look and feel icon for warning dialogs | | 错误 | The Java look and feel icon for error dialogs | The Windows look and feel icon for error dialogs |

对于大多数简单的模态对话框,您可以使用JOptionPaneshow _Xxx_ Dialog方法之一创建和显示对话框。如果您的对话框应该是内部框架,则在show之后添加Internal - 例如,showMessageDialog更改为showInternalMessageDialog。如果您需要控制对话框窗口关闭行为或者您不希望对话框是模态的,那么您应该直接实例化JOptionPane并将其添加到JDialog实例。然后调用JDialog上的setVisible(true)使其显示。

两个最有用的显示 _Xxx_ 对话方法是showMessageDialogshowOptionDialogshowMessageDialog方法显示简单的单键对话框。 showOptionDialog方法显示自定义对话框 - 它可以显示带有自定义按钮文本的各种按钮,并且可以包含标准文本消息或组件集合。

另外两个显示 _Xxx_ Dialog方法的使用频率较低。 showConfirmDialog方法要求用户确认某些内容,但会显示标准按钮文本(例如,是/否或本地化的等效文本),而不是根据用户情况自定义的按钮文本(例如,启动/取消)。第四种方法showInputDialog用于显示模式对话框,该对话框使用文本字段,不可编辑的组合框或列表从用户获取字符串。

以下是从 DialogDemo.java 中使用showMessageDialogshowOptionDialogJOptionPane构造器的一些示例。有关更多示例代码,请参阅 DialogDemo.java 以及使用对话框的示例中列出的其他程序。

showMessageDialog

Displays a modal dialog with one button, which is labeled “OK” (or the localized equivalent). You can easily specify the message, icon, and title that the dialog displays. Here are some examples of using showMessageDialog:

Informational dialog with default title and icon

  1. //default title and icon
  2. JOptionPane.showMessageDialog(frame,
  3. "Eggs are not supposed to be green.");

Informational dialog with custom title, warning icon |

  1. //custom title, warning icon
  2. JOptionPane.showMessageDialog(frame,
  3. "Eggs are not supposed to be green.",
  4. "Inane warning",
  5. JOptionPane.WARNING_MESSAGE);

Informational dialog with custom title, error icon |

  1. //custom title, error icon
  2. JOptionPane.showMessageDialog(frame,
  3. "Eggs are not supposed to be green.",
  4. "Inane error",
  5. JOptionPane.ERROR_MESSAGE);

Informational dialog with custom title, no icon |

  1. //custom title, no icon
  2. JOptionPane.showMessageDialog(frame,
  3. "Eggs are not supposed to be green.",
  4. "A plain message",
  5. JOptionPane.PLAIN_MESSAGE);

Informational dialog with custom title, custom icon |

  1. //custom title, custom icon
  2. JOptionPane.showMessageDialog(frame,
  3. "Eggs are not supposed to be green.",
  4. "Inane custom dialog",
  5. JOptionPane.INFORMATION_MESSAGE,
  6. icon);

showOptionDialog

Displays a modal dialog with the specified buttons, icons, message, title, and so on. With this method, you can change the text that appears on the buttons of standard dialogs. You can also perform many other kinds of customization.

Yes/No/Cancel (in different words); showOptionDialog

  1. //Custom button text
  2. Object[] options = {"Yes, please",
  3. "No, thanks",
  4. "No eggs, no ham!"};
  5. int n = JOptionPane.showOptionDialog(frame,
  6. "Would you like some green eggs to go "
  7. + "with that ham?",
  8. "A Silly Question",
  9. JOptionPane.YES_NO_CANCEL_OPTION,
  10. JOptionPane.QUESTION_MESSAGE,
  11. null,
  12. options,
  13. options[2]);

JOptionPane (constructor)

Creates a JOptionPane with the specified buttons, icons, message, title, and so on. You must then add the option pane to a JDialog, register a property-change listener on the option pane, and show the dialog. See Stopping Automatic Dialog Closing for details.

Explicitly used the JOptionPane constructor

  1. final JOptionPane optionPane = new JOptionPane(
  2. "The only way to close this dialog is by\n"
  3. + "pressing one of the following buttons.\n"
  4. + "Do you understand?",
  5. JOptionPane.QUESTION_MESSAGE,
  6. JOptionPane.YES_NO_OPTION);

尽管每个方法和构造器的参数数量各不相同,但所有显示 _Xxx_ Dialog方法和JOptionPane构造器的参数都是标准化的。以下列表描述了每个参数。要查看特定方法的确切参数列表,请参阅 Dialog API

Component _parentComponent_

The first argument to each show_Xxx_Dialog method is always the parent component, which must be a Frame, a component inside a Frame, or null. If you specify a Frame or Dialog, then the Dialog will appear over the center of the Frame and follow the focus behavior of that Frame. If you specify a component inside a Frame, then the Dialog will appear over the center of that component and will follow the focus behavior of that component’s Frame. If you specify null, then the look and feel will pick an appropriate position for the dialog — generally the center of the screen — and the Dialog will not necessarily follow the focus behavior of any visible Frame or Dialog.

JOptionPane构造器不包含此参数。而是在创建包含JOptionPaneJDialog时指定父框架,并使用JDialog setLocationRelativeTo方法设置对话框位置。

Object _message_

This required argument specifies what the dialog should display in its main area. Generally, you specify a string, which results in the dialog displaying a label with the specified text. You can split the message over several lines by putting newline (\n) characters inside the message string. For example:

  1. "Complete the sentence:\n \"Green eggs and...\""

String _title_

The title of the dialog.

int _optionType_

Specifies the set of buttons that appear at the bottom of the dialog. Choose from one of the following standard sets: DEFAULT_OPTION, YES_NO_OPTION, YES_NO_CANCEL_OPTION, OK_CANCEL_OPTION.

int _messageType_

This argument determines the icon displayed in the dialog. Choose from one of the following values: PLAIN_MESSAGE (no icon), ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE.

Icon _icon_

The icon to display in the dialog.

Object[] _options_

Generally used to specify the string displayed by each button at the bottom of the dialog. See Customizing Button Text in a Standard Dialog for more information. Can also be used to specify icons to be displayed by the buttons or non-button components to be added to the button row.

Object _initialValue_

Specifies the default value to be selected.

您可以让选项窗格显示其默认图标,也可以使用消息类型或图标参数指定图标。默认情况下,使用showMessageDialog创建的选项窗格显示信息图标,使用showConfirmDialogshowInputDialog创建的选项窗格显示问题图标,使用JOptionPane构造器创建的选项窗格不显示图标。要指定对话框显示标准图标或不显示图标,请指定与所需图标对应的消息类型。要指定自定义图标,请使用 icon 参数。 icon 参数优先于消息类型;只要 icon 参数具有非 null 值,对话框就会显示指定的图标。

使用JOptionPane创建对话框时,可以使用标准按钮文本(可能因外观和区域设置而异)或指定不同的文本。默认情况下,选项窗格类型确定显示的按钮数。例如,YES_NO_OPTION对话框有两个按钮,YES_NO_CANCEL_OPTION对话框有三个按钮。

以下代码取自 DialogDemo.java ,创建两个是/否对话框。第一个对话框用showConfirmDialog实现,它使用两个按钮的外观措辞。第二个对话框使用showOptionDialog,因此它可以自定义措辞。除了措辞更改,对话框是相同的。

A yes/no dialog, in those words [but perhaps translated]

  1. //default icon, custom title
  2. int n = JOptionPane.showConfirmDialog(
  3. frame,
  4. "Would you like green eggs and ham?",
  5. "An Inane Question",
  6. JOptionPane.YES_NO_OPTION);

A yes/no dialog -- in other words |

  1. Object[] options = {"Yes, please",
  2. "No way!"};
  3. int n = JOptionPane.showOptionDialog(frame,
  4. "Would you like green eggs and ham?",
  5. "A Silly Question",
  6. JOptionPane.YES_NO_OPTION,
  7. JOptionPane.QUESTION_MESSAGE,
  8. null, //do not use a custom Icon
  9. options, //the titles of buttons
  10. options[0]); //default button title

如前面的代码片段所示,showMessageDialogshowConfirmDialogshowOptionDialog方法返回一个表示用户选择的整数。该整数的值为YES_OPTIONNO_OPTIONCANCEL_OPTIONOK_OPTIONCLOSED_OPTION。除CLOSED_OPTION外,每个选项对应于用户按下的按钮。返回CLOSED_OPTION时,表示用户明确关闭了对话框窗口,而不是选择选项窗格内的按钮。

即使您更改标准对话框按钮显示的字符串,返回值仍然是预定义的整数之一。例如,YES_NO_OPTION对话框始终返回以下值之一:YES_OPTIONNO_OPTIONCLOSED_OPTION

获取用户输入

显示 _Xxx_ 对话的唯一形式是不返回整数showInputDialog,而是返回ObjectObject通常是反映用户选择的String。下面是使用showInputDialog创建一个对话框的示例,该对话框允许用户选择三个字符串中的一个:

An input dialog with a combo box

  1. Object[] possibilities = {"ham", "spam", "yam"};
  2. String s = (String)JOptionPane.showInputDialog(
  3. frame,
  4. "Complete the sentence:\n"
  5. + "\"Green eggs and...\"",
  6. "Customized Dialog",
  7. JOptionPane.PLAIN_MESSAGE,
  8. icon,
  9. possibilities,
  10. "ham");
  11. //If a string was returned, say so.
  12. if ((s != null) && (s.length() > 0)) {
  13. setLabel("Green eggs and... " + s + "!");
  14. return;
  15. }
  16. //If you're here, the return value was null/empty.
  17. setLabel("Come on, finish the sentence!");

如果您不想限制用户的选择,您可以使用showInputDialog方法的形式,该方法使用较少的参数或为对象数组指定null。在 Java 外观中,用null代替possibilities会产生一个带有文本字段的对话框,如下所示:

An input dialog with a text field

由于用户可以在文本字段中键入任何内容,因此您可能需要检查返回的值并要求用户在无效时再次尝试。另一种方法是创建一个自定义对话框,在返回之前验证用户输入的数据。有关验证数据的示例,请参见 CustomDialog.java

如果您正在设计自定义对话框,则需要设计对话框的 API,以便查询用户选择的对话框。例如,CustomDialog具有getValidatedText方法,该方法返回用户输入的文本。

默认情况下,当用户单击JOptionPane创建的按钮时,对话框将关闭。但是如果你想在关闭对话框之前检查用户的答案怎么办?在这种情况下,您必须实现自己的属性更改监听器,以便在用户单击按钮时,对话框不会自动关闭。

DialogDemo包含两个实现属性更改监听器的对话框。其中一个对话框是自定义模式对话框,在 CustomDialog 中实现,它使用JOptionPane来获取标准图标并获得布局帮助。另一个对话框,其代码如下,使用标准是/否JOptionPane。尽管此对话框在编写时相当无用,但其代码非常简单,您可以将其用作更复杂对话框的模板。

除了设置属性更改监听器之外,以下代码还调用JDialogsetDefaultCloseOperation方法并实现一个窗口监听器,该窗口监听器正确处理窗口关闭尝试。如果您不关心在用户明确关闭窗口时收到通知,则忽略粗体代码。

  1. final JOptionPane optionPane = new JOptionPane(
  2. "The only way to close this dialog is by\n"
  3. + "pressing one of the following buttons.\n"
  4. + "Do you understand?",
  5. JOptionPane.QUESTION_MESSAGE,
  6. JOptionPane.YES_NO_OPTION);
  7. final JDialog dialog = new JDialog(frame,
  8. "Click a button",
  9. true);
  10. dialog.setContentPane(optionPane);
  11. dialog.setDefaultCloseOperation(
  12. JDialog.DO_NOTHING_ON_CLOSE);
  13. dialog.addWindowListener(new WindowAdapter() {
  14. public void windowClosing(WindowEvent we) {
  15. setLabel("Thwarted user attempt to close window.");
  16. }
  17. });
  18. optionPane.addPropertyChangeListener(
  19. new PropertyChangeListener() {
  20. public void propertyChange(PropertyChangeEvent e) {
  21. String prop = e.getPropertyName();
  22. if (dialog.isVisible()
  23. && (e.getSource() == optionPane)
  24. && (prop.equals(JOptionPane.VALUE_PROPERTY))) {
  25. //If you were going to check something
  26. //before closing the window, you'd do
  27. //it here.
  28. dialog.setVisible(false);
  29. }
  30. }
  31. });
  32. dialog.pack();
  33. dialog.setVisible(true);
  34. int value = ((Integer)optionPane.getValue()).intValue();
  35. if (value == JOptionPane.YES_OPTION) {
  36. setLabel("Good.");
  37. } else if (value == JOptionPane.NO_OPTION) {
  38. setLabel("Try using the window decorations "
  39. + "to close the non-auto-closing dialog. "
  40. + "You can't!");
  41. }

下表列出了常用的JOptionPaneJDialog构造器和方法。您可能会调用的其他方法由 DialogWindowComponent 类定义,包括packsetSizesetVisible

API 列出如下:

方法 目的
static void showMessageDialog(Component,Object)

static void showMessageDialog(Component,Object,String,int) static void showMessageDialog(Component,Object,String ,int,Icon) | 显示一键式模态对话框,为用户提供一些信息。参数指定(按顺序)对话框的父组件,消息,标题,消息类型和图标。有关参数及其效果的讨论,请参见创建和显示简单对话框。 | | static int showOptionDialog(Component,Object,String,int,int,Icon,Object [],Object) | 显示自定义模式对话框。参数指定(按顺序)父组件,消息,标题,选项类型,消息类型,图标,选项和对话框的初始值。有关参数及其效果的讨论,请参见创建和显示简单对话框。 | | static int showConfirmDialog(Component,Object) static int showConfirmDialog(Component,Object,String,int) static int showConfirmDialog(Component,Object,String) ,int,int) static int showConfirmDialog(Component,Object,String,int,int,Icon) | 显示一个模式对话框,询问用户一个问题。参数指定(按顺序)对话框的父组件,消息,标题,选项类型,消息类型和图标。有关参数及其效果的讨论,请参见创建和显示简单对话框。 | | static String showInputDialog(Object) static String showInputDialog(Component,Object) static String showInputDialog(Component,Object,String,int) 静态字符串 showInputDialog(Component,Object,String,int,Icon,Object [],Object) | 显示一个提示用户输入的模式对话框。单参数版本仅指定消息,假定父组件为空。其他版本的参数指定(按顺序)父组件,消息,标题,消息类型,图标,选项和对话框的初始值。有关参数及其效果的讨论,请参见创建和显示简单对话框。 | | static void showInternalMessageDialog(…) static void showInternalOptionDialog(…) static void showInternalConfirmDialog(…) 静态字符串 showInternalInputDialog(…) | 将标准对话框实现为内部框架。有关参数的确切列表,请参见 JOptionPane API 文档。 |

方法或构造器 目的
JOptionPane()

JOptionPane(对象) JOptionPane(Object,int) JOptionPane(Object,int,int ) JOptionPane(Object,int,int,Icon) JOptionPane(Object,int,int,Icon,Object []) JOptionPane(Object,int,int,Icon,Object [],Object) | 创建JOptionPane实例。有关参数及其效果的讨论,请参见创建和显示简单对话框。 | | 静态帧 getFrameForComponent(组件) 静态 JDesktopPane getDesktopPaneForComponent(组件) | Handy JOptionPane类方法,分别找到指定组件所在的桌面窗格。 | | int getMaxCharactersPerLineCount() | 确定在选项窗格文本中自动插入换行符的位置。 (默认值为Integer.MAX_VALUE。)要使用此方法,必须创建JOptionPane子类。例如,以下代码会生成一个选项窗格,每行一个单词,因为字符串中的每个单词都是 5 个字符或更少 |

  1. JOptionPane op = new JOptionPane("This is the text.") {
  2. public int getMaxCharactersPerLineCount() {
  3. return 5;
  4. }
  5. };
方法或构造器 目的
JDialog()

JDialog(Dialog) JDialog(Dialog,boolean) JDialog(Dialog,String) JDialog(对话框,字符串,布尔) JDialog(对话框,字符串,布尔,图形配置) JDialog(框架) JDialog(帧,布尔) JDialog(帧,字符串) JDialog(帧,字符串,布尔) JDialog(Frame,String,boolean,GraphicsConfiguration) JDialog(Window owner) JDialog(Window owner,Dialog.ModalityType modalityType) JDialog(Window owner,String title) JDialog(Window owner,String title,Dialog.ModalityType modalityType) JDialog(Window owner,字符串标题,Dialog.ModalityType modalityType,GraphicsConfiguration gc) | 创建JDialog实例。 Frame参数(如果有)是对话框所依赖的帧(通常是JFrame对象)。使布尔参数true指定模态对话框,false或不存在以指定非模态对话框。您还可以使用字符串参数指定对话框的标题。 | | void setContentPane(Container) Container getContentPane() | 获取并设置内容窗格,该窗格通常是所有对话框组件的容器。有关详细信息,请参阅使用顶级容器。 | | void setDefaultCloseOperation(int) int getDefaultCloseOperation() | 获取并设置用户尝试关闭对话框时发生的情况。可能的值:DISPOSE_ON_CLOSEDO_NOTHING_ON_CLOSEHIDE_ON_CLOSE(默认值)。有关详细信息,请参阅响应窗口关闭事件。 | | void setLocationRelativeTo(Component) | 将对话框置于指定组件的中心。 | | static void setDefaultLookAndFeelDecorated(boolean) static boolean isDefaultLookAndFeelDecorated() | 设置或获取关于对话框的窗口装饰(例如边框或关闭窗口的窗口小部件)是否应由当前外观提供的提示。否则,对话框的装饰将由当前窗口管理器提供。有关详细信息,请参阅指定窗口装饰。 |

示例

此表列出了使用JOptionPaneJDialog的示例。要查找使用对话框的其他示例,请参阅进度条颜色选择器文件选择器的示例列表。

在哪里描述 笔记
DialogDemo

CustomDialog | 这个部分 | 使用JOptionPaneJDialog创建多种对话框。 | | Framework | - | 当用户选择退出菜单项时,显示确认对话框。 | | ListDialog | 如何使用 BoxLayout | 实现包含滚动列表和两个按钮的模式对话框。除实用方法getFrameForComponent外,不使用JOptionPane。 |