Documentation

The Java™ Tutorials
Hide TOC
How to Make Dialogs如何制作对话框
Trail: Creating a GUI With Swing
Lesson: Using Swing Components
Section: How to Use Various Components

How to Make Dialogs如何制作对话框

A Dialog window is an independent sub window meant to carry temporary notice apart from the main Swing Application Window. 对话框窗口是一个独立的子窗口,用于在主Swing应用程序窗口之外携带临时通知。Most Dialogs present an error message or warning to a user, but Dialogs can present images, directory trees, or just about anything compatible with the main Swing Application that manages them.大多数对话框向用户显示错误消息或警告,但对话框可以显示图像、目录树或与管理它们的主Swing应用程序兼容的任何内容。

For convenience, several Swing component classes can directly instantiate and display dialogs. 为了方便起见,几个Swing组件类可以直接实例化和显示对话框。To create simple, standard dialogs, you use the JOptionPane class. 要创建简单的标准对话框,可以使用JOptionPane类。The ProgressMonitor class can put up a dialog that shows the progress of an operation. ProgressMonitor类可以设置一个对话框,显示操作的进度。Two other classes, JColorChooser and JFileChooser, also supply standard dialogs. 另外两个类JColorChooserJFileChooser也提供标准对话框。To bring up a print dialog, you can use the Printing API. 要打开打印对话框,可以使用打印API。To create a custom dialog, use the JDialog class directly.要创建自定义对话框,请直接使用JDialog类。

The code for simple dialogs can be minimal. 简单对话框的代码可以是最少的。For example, here is an informational dialog:例如,下面是一个信息对话框:

An informational dialog requires minimal code

Here is the code that creates and shows it:下面是创建并显示它的代码:

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

The rest of this section covers the following topics:本节其余部分包括以下主题:

An Overview of Dialogs对话概述

Every dialog is dependent on a Frame component. 每个对话框都依赖于框架构件。When that Frame is destroyed, so are its dependent Dialogs. 当该帧被破坏时,其相关对话框也被破坏。When the frame is iconified, its dependent Dialogs also disappear from the screen. 当框架图标化时,其相关对话框也从屏幕上消失。When the frame is deiconified, its dependent Dialogs return to the screen. 当帧被去锥形化时,其相关对话框返回到屏幕。A swing JDialog class inherits this behavior from the AWT Dialog class.swing JDialog类从AWTDialog类继承此行为。

A Dialog can be modal. 对话框可以是模态的When a modal Dialog is visible, it blocks user input to all other windows in the program. 当模式对话框可见时,它会阻止用户输入程序中的所有其他窗口。JOptionPane creates JDialogs that are modal. JOptionPane创建模态的JDialogTo create a non-modal Dialog, you must use the JDialog class directly.要创建非模态对话框,必须直接使用JDialog类。

Starting with JDK 7, you can modify dialog window modality behavior using the new Modality API. 从JDK 7开始,您可以使用新的模态API修改对话框窗口模态行为。See The New Modality API for details.有关详细信息,请参阅新的模态API

The JDialog class is a subclass of the AWT java.awt.Dialog class. JDialog类是AWT java.awt.Dialog类的一个子类。It adds a root pane container and support for a default close operation to the Dialog object . 它为Dialog对象添加了根窗格容器和对默认关闭操作的支持。These are the same features that JFrame has, and using JDialog directly is very similar to using JFrame. 这些功能与JFrame相同,直接使用JDialog与使用JFrame非常相似。If you're going to use JDialog directly, then you should understand the material in Using Top-Level Containers and How to Make Frames, especially Responding to Window-Closing Events.如果您打算直接使用JDialog,那么您应该了解使用顶级容器的材料,以及如何制作框架,尤其是响应窗口关闭事件

Even when you use JOptionPane to implement a dialog, you're still using a JDialog behind the scenes. 即使使用JOptionPane实现对话框,您仍然在幕后使用JDialog。The reason is that JOptionPane is simply a container that can automatically create a JDialog and add itself to the JDialog's content pane.原因是JOptionPane只是一个容器,可以自动创建JDialog并将其自身添加到JDialog的内容窗格中。

The DialogDemo ExampleDialogDemo示例

Here is a picture of an application that displays dialogs.下面是显示对话框的应用程序的图片。

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). 单击启动按钮,使用Java™Web启动运行对话框演示(下载JDK 7或更高版本)。Alternatively, to compile and run the example yourself, consult the example index.或者,要自己编译和运行示例,请参考示例索引Launches the DialogDemo example

  2. Click the Show it! button.点击显示它!按钮
    A modal dialog will appear. 将出现一个模式对话框。Until you close it, the application will be unresponsive, although it will repaint itself if necessary. 在您关闭它之前,应用程序将没有响应,尽管它将在必要时重新绘制自身。You can close the dialog either by clicking a button in the dialog or explicitly, such as by using the dialog window decorations.您可以通过单击对话框中的按钮或显式关闭对话框,例如使用对话框窗口装饰。
  3. In the More Dialogs pane, click the bottom radio button and then the Show it! button.在“更多对话框”窗格中,单击底部单选按钮,然后单击“显示它!”!按钮
    A non-modal dialog will appear. Note that the DialogDemo window remains fully functional while the non-modal dialog is up.将出现一个非模态对话框。请注意,当非模态对话框打开时,DialogDemo窗口保持完全功能。
  4. While the non-modal dialog is showing, iconify the DialogDemo window.显示非模态对话框时,将对话框演示窗口图标化。
    The dialog will disappear from the screen until you deiconify the DialogDemo window.对话框将从屏幕上消失,直到您取消对话框演示窗口。

JOptionPane FeaturesJOptionPane功能

Using JOptionPane, you can quickly create and customize several different kinds of dialogs. 使用JOptionPane,您可以快速创建和自定义几种不同类型的对话框。JOptionPane provides support for laying out standard dialogs, providing icons, specifying the dialog title and text, and customizing the button text. 提供对布局标准对话框、提供图标、指定对话框标题和文本以及自定义按钮文本的支持。Other features allow you to customize the components the dialog displays and specify where the dialog should appear onscreen. 其他功能允许您自定义对话框显示的组件,并指定对话框在屏幕上的显示位置。You can even specify that an option pane put itself into an internal frame (JInternalFrame) instead of a JDialog.您甚至可以指定选项窗格将自身置于内部框架JInternalFrame)中,而不是JDialog中。

When you create a JOptionPane, look-and-feel-specific code adds components to the JOptionPane and determines the layout of those components.创建JOptionPane时,特定于外观的代码将组件添加到JOptionPane,并确定这些组件的布局。

JOptionPane's icon support lets you easily specify which icon the dialog displays. JOptionPane的图标支持允许您轻松指定对话框显示的图标。You can use a custom icon, no icon at all, or any one of four standard JOptionPane icons (question, information, warning, and error). 您可以使用自定义图标、完全不使用图标或四个标准JOptionPane图标(问题、信息、警告和错误)中的任何一个。Each look and feel has its own versions of the four standard icons. 每个外观都有四个标准图标的各自版本。The following figure shows the icons used in the Java (and Windows) look and feel.下图显示了Java(和Windows)外观中使用的图标。

Icons used by JOptionPaneJOptionPane使用的图标
Icon description图标描述 Java look and feelJava外观 Windows look and feelWindows外观
question The Java look and feel icon for dialogs that ask questions The Windows look and feel icon for dialogs that ask questions
information The Java look and feel icon for informational dialogs The Windows look and feel icon for informational dialogs
warning The Java look and feel icon for warning dialogs The Windows look and feel icon for warning dialogs
error The Java look and feel icon for error dialogs The Windows look and feel icon for error dialogs

Creating and Showing Simple Dialogs创建和显示简单对话框

For most simple modal dialogs, you create and show the dialog using one of JOptionPane's showXxxDialog methods. 对于大多数简单的模式对话框,您可以使用JOptionPaneshowXxxDialog方法之一创建和显示对话框。If your dialog should be an internal frame, then add Internal after show — for example, showMessageDialog changes to showInternalMessageDialog. 如果您的对话框应该是内部框架,则在show后面添加Internal—例如,showMessageDialog更改为showInternalMessageDialogIf you need to control the dialog window-closing behavior or if you do not want the dialog to be modal, then you should directly instantiate JOptionPane and add it to a JDialog instance. 如果您需要控制对话框窗口的关闭行为,或者您不希望对话框处于模态状态,那么您应该直接实例化JOptionPane并将其添加到JDialog实例中。Then invoke setVisible(true) on the JDialog to make it appear.然后在JDialog上调用setVisible(true)使其显示。

The two most useful showXxxDialog methods are showMessageDialog and showOptionDialog. 两种最有用的showXxxDialog方法是showMessageDialogshowOptionDialogThe showMessageDialog method displays a simple, one-button dialog. showMessageDialog方法显示一个简单的单键对话框。The showOptionDialog method displays a customized dialog — it can display a variety of buttons with customized button text, and can contain a standard text message or a collection of components.showOptionDialog方法显示自定义对话框—它可以显示带有自定义按钮文本的各种按钮,并且可以包含标准文本消息或组件集合。

The other two showXxxDialog methods are used less often. 其他两种showXxxDialog方法的使用频率较低。The showConfirmDialog method asks the user to confirm something, but presents standard button text (Yes/No or the localized equivalent, for example) rather than button text customized to the user situation (Start/Cancel, for example). showConfirmDialog方法要求用户确认某些内容,但显示标准按钮文本(例如,是/否或本地化的等效文本),而不是根据用户情况定制的按钮文本(比如,开始/取消)。A fourth method, showInputDialog, is designed to display a modal dialog that gets a string from the user, using either a text field, an uneditable combo box or a list.第四种方法showInputDialog用于显示一个模式对话框,该对话框使用文本字段、不可编辑的组合框或列表从用户处获取字符串。

Here are some examples, taken from DialogDemo.java, of using showMessageDialog, showOptionDialog, and the JOptionPane constructor. 下面是一些使用showMessageDialogshowOptionDialogJOptionPane构造函数的示例,这些示例取自DialogDemo.javaFor more example code, see DialogDemo.java and the other programs listed in Examples that Use Dialogs.有关更多示例代码,请参阅DialogDemo.java使用对话框的示例中列出的其他程序。

showMessageDialog
Displays a modal dialog with one button, which is labeled "OK" (or the localized equivalent). 显示一个带有一个按钮的模式对话框,该对话框标记为“OK”(或本地化的等效按钮)。You can easily specify the message, icon, and title that the dialog displays. 您可以轻松指定对话框显示的消息、图标和标题。Here are some examples of using showMessageDialog:以下是使用showMessageDialog的一些示例:
Informational dialog with default title and icon
//default title and icon
JOptionPane.showMessageDialog(frame,
    "Eggs are not supposed to be green.");
Informational dialog with custom title, warning icon
//custom title, warning icon
JOptionPane.showMessageDialog(frame,
    "Eggs are not supposed to be green.",
    "Inane warning",
    JOptionPane.WARNING_MESSAGE);
Informational dialog with custom title, error icon
//custom title, error icon
JOptionPane.showMessageDialog(frame,
    "Eggs are not supposed to be green.",
    "Inane error",
    JOptionPane.ERROR_MESSAGE);
Informational dialog with custom title, no icon
//custom title, no icon
JOptionPane.showMessageDialog(frame,
    "Eggs are not supposed to be green.",
    "A plain message",
    JOptionPane.PLAIN_MESSAGE);
Informational dialog with custom title, custom icon
//custom title, custom icon
JOptionPane.showMessageDialog(frame,
    "Eggs are not supposed to be green.",
    "Inane custom dialog",
    JOptionPane.INFORMATION_MESSAGE,
    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
//Custom button text
Object[] options = {"Yes, please",
                    "No, thanks",
                    "No eggs, no ham!"};
int n = JOptionPane.showOptionDialog(frame,
    "Would you like some green eggs to go "
    + "with that ham?",
    "A Silly Question",
    JOptionPane.YES_NO_CANCEL_OPTION,
    JOptionPane.QUESTION_MESSAGE,
    null,
    options,
    options[2]);
JOptionPane (constructor)
Creates a JOptionPane with the specified buttons, icons, message, title, and so on. 使用指定的按钮、图标、消息、标题等创建JOptionPaneYou must then add the option pane to a JDialog, register a property-change listener on the option pane, and show the dialog. 然后,必须将选项窗格添加到JDialog,在选项窗格上注册属性更改侦听器,并显示对话框。See Stopping Automatic Dialog Closing for details. 有关详细信息,请参阅停止自动对话框关闭
Explicitly used the JOptionPane constructor
final JOptionPane optionPane = new JOptionPane(
    "The only way to close this dialog is by\n"
    + "pressing one of the following buttons.\n"
    + "Do you understand?",
    JOptionPane.QUESTION_MESSAGE,
    JOptionPane.YES_NO_OPTION);

The arguments to all of the showXxxDialog methods and JOptionPane constructors are standardized, though the number of arguments for each method and constructor varies. 所有showXxxDialog方法和JOptionPane构造函数的参数都是标准化的,尽管每个方法和构造函数的参数数量各不相同。The following list describes each argument. 下表描述了每个参数。To see the exact list of arguments for a particular method, see The Dialog API.要查看特定方法的参数的确切列表,请参阅对话框API

Component parentComponent
The first argument to each showXxxDialog method is always the parent component, which must be a Frame, a component inside a Frame, or null. 每个showXxxDialog方法的第一个参数始终是父组件,它必须是框架、框架内的组件或nullIf 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. 如果指定null,则外观将为对话框选择适当的位置—通常是屏幕的中心—并且该对话框不必遵循任何可见帧或对话框的聚焦行为。

The JOptionPane constructors do not include this argument. JOptionPane构造函数不包含此参数。Instead, you specify the parent frame when you create the JDialog that contains the JOptionPane, and you use the JDialog setLocationRelativeTo method to set the dialog position.相反,您可以在创建包含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. 通过在消息字符串中添加换行符(\n),可以将消息拆分为多行。For example:例如:
"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.从以下标准集中选择一个:DEFAULT_OPTIONYES_NO_OPTIONYES_NO_CANCEL_OPTIONOK_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.从以下值中选择一个:PLAIN_MESSAGE(无图标)、ERROR_MESSAGEINFORMATION_MESSAGEWARNING_MESSAGEQUESTION_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.指定要选择的默认值。

You can either let the option pane display its default icon or specify the icon using the message type or icon argument. 您可以让选项窗格显示其默认图标,也可以使用消息类型或图标参数指定图标。By default, an option pane created with showMessageDialog displays the information icon, one created with showConfirmDialog or showInputDialog displays the question icon, and one created with a JOptionPane constructor displays no icon. 默认情况下,使用showMessageDialog创建的选项窗格显示信息图标,使用showConfirmDialogshowInputDialog创建一个选项窗格显示问题图标,使用JOptionPane构造函数创建的选项面板不显示图标。To specify that the dialog display a standard icon or no icon, specify the message type corresponding to the icon you desire. 要指定对话框显示标准图标或无图标,请指定与所需图标对应的消息类型。To specify a custom icon, use the icon argument. 要指定自定义图标,请使用图标参数。The icon argument takes precedence over the message type; as long as the icon argument has a non-null value, the dialog displays the specified icon.图标参数优先于消息类型;只要icon参数具有非空值,对话框就会显示指定的图标。

Customizing Button Text自定义按钮文本

When you use JOptionPane to create a dialog, you can either use the standard button text (which might vary by look and feel and locale) or specify different text. 使用JOptionPane创建对话框时,您可以使用标准按钮文本(可能因外观和区域设置而有所不同),也可以指定不同的文本。By default, the option pane type determines how many buttons appear. 默认情况下,选项窗格类型决定显示多少按钮。For example, YES_NO_OPTION dialogs have two buttons, and YES_NO_CANCEL_OPTION dialogs have three buttons.例如,YES_NO_OPTION对话框有两个按钮,而YES_NO_CANCEL_OPTION对话框有三个按钮。

The following code, taken from DialogDemo.java, creates two Yes/No dialogs. 下面的代码取自DialogDemo.java,创建了两个是/否对话框。The first dialog is implemented with showConfirmDialog, which uses the look-and-feel wording for the two buttons. 第一个对话框由showConfirmDialog实现,它使用了两个按钮的外观措辞。The second dialog uses showOptionDialog so it can customize the wording. 第二个对话框使用showOptionDialog,因此可以自定义措辞。With the exception of wording changes, the dialogs are identical.除了措辞变化外,对话框是相同的。

A yes/no dialog, in those words [but perhaps translated]
//default icon, custom title
int n = JOptionPane.showConfirmDialog(
    frame,
    "Would you like green eggs and ham?",
    "An Inane Question",
    JOptionPane.YES_NO_OPTION);
A yes/no dialog -- in other words
Object[] options = {"Yes, please",
                    "No way!"};
int n = JOptionPane.showOptionDialog(frame,
    "Would you like green eggs and ham?",
    "A Silly Question",
    JOptionPane.YES_NO_OPTION,
    JOptionPane.QUESTION_MESSAGE,
    null,     //do not use a custom Icon
    options,  //the titles of buttons
    options[0]); //default button title

As the previous code snippets showed, the showMessageDialog, showConfirmDialog, and showOptionDialog methods return an integer indicating the user's choice. 如前面的代码片段所示,showMessageDialogshowConfirmDialogshowOptionDialog方法返回一个指示用户选择的整数。The values for this integer are YES_OPTION, NO_OPTION, CANCEL_OPTION, OK_OPTION, and CLOSED_OPTION. 该整数的值为YES_OPTIONNO_OPTIONCANCEL_OPTIONOK_OPTIONCLOSED_OPTIONExcept for CLOSED_OPTION, each option corresponds to the button the user pressed. 除了CLOSED_OPTION之外,每个选项都对应于用户按下的按钮。When CLOSED_OPTION is returned, it indicates that the user closed the dialog window explicitly, rather than by choosing a button inside the option pane.返回CLOSED_OPTION时,表示用户显式关闭对话框窗口,而不是在选项窗格中选择按钮。

Even if you change the strings that the standard dialog buttons display, the return value is still one of the pre-defined integers. 即使更改了标准对话框按钮显示的字符串,返回值仍然是预定义的整数之一。For example, a YES_NO_OPTION dialog always returns one of the following values: YES_OPTION, NO_OPTION, or CLOSED_OPTION.例如,YES_NO_OPTION对话框始终返回以下值之一:YES_OPTIONNO_OPTIONCLOSED_OPTION

Getting the User's Input from a Dialog从对话框获取用户输入

The only form of showXxxDialog that does not return an integer is showInputDialog, which returns an Object instead. showXxxDialog唯一不返回整数的形式是showInputDialog,它返回一个对象。This Object is generally a String reflecting the user's choice. Object通常是反映用户选择的StringHere is an example of using showInputDialog to create a dialog that lets the user choose one of three strings:下面是一个使用showInputDialog创建对话框的示例,该对话框允许用户从三个字符串中选择一个:

An input dialog with a combo box
Object[] possibilities = {"ham", "spam", "yam"};
String s = (String)JOptionPane.showInputDialog(
                    frame,
                    "Complete the sentence:\n"
                    + "\"Green eggs and...\"",
                    "Customized Dialog",
                    JOptionPane.PLAIN_MESSAGE,
                    icon,
                    possibilities,
                    "ham");

//If a string was returned, say so.
if ((s != null) && (s.length() > 0)) {
    setLabel("Green eggs and... " + s + "!");
    return;
}

//If you're here, the return value was null/empty.
setLabel("Come on, finish the sentence!");

If you do not care to limit the user's choices, you can either use a form of the showInputDialog method that takes fewer arguments or specify null for the array of objects. 如果您不想限制用户的选择,您可以使用使用较少参数的showInputDialog方法,或者为对象数组指定nullIn the Java look and feel, substituting null for possibilities results in a dialog that has a text field and looks like this:在Java look and feel中,用null替换possibilities会导致一个对话框,该对话框具有文本字段,如下所示:

An input dialog with a text field

Because the user can type anything into the text field, you might want to check the returned value and ask the user to try again if it is invalid. 由于用户可以在文本字段中键入任何内容,因此您可能需要检查返回的值,并要求用户在该值无效时重试。Another approach is to create a custom dialog that validates the user-entered data before it returns. 另一种方法是创建一个自定义对话框,在返回之前验证用户输入的数据。See CustomDialog.java for an example of validating data.有关验证数据的示例,请参阅CustomDialog.java

If you're designing a custom dialog, you need to design your dialog's API so that you can query the dialog about what the user chose. 如果要设计自定义对话框,则需要设计对话框的API,以便可以查询用户选择的对话框。For example, CustomDialog has a getValidatedText method that returns the text the user entered.例如,CustomDialog有一个getValidatedText方法,该方法返回用户输入的文本。

Stopping Automatic Dialog Closing停止自动对话框关闭

By default, when the user clicks a JOptionPane-created button, the dialog closes. 默认情况下,当用户单击创建的JOptionPane按钮时,对话框将关闭。But what if you want to check the user's answer before closing the dialog? 但是,如果您想在关闭对话框之前检查用户的答案,该怎么办?In this case, you must implement your own property change listener so that when the user clicks a button, the dialog does not automatically close.在这种情况下,您必须实现自己的属性更改侦听器,以便当用户单击按钮时,对话框不会自动关闭。

DialogDemo contains two dialogs that implement a property change listener. 包含两个实现属性更改侦听器的对话框。One of these dialogs is a custom modal dialog, implemented in CustomDialog, that uses JOptionPane both to get the standard icon and to get layout assistance. 其中一个对话框是在CustomDialog中实现的自定义模式对话框,它使用JOptionPane来获取标准图标和布局帮助。The other dialog, whose code is below, uses a standard Yes/No JOptionPane. 另一个对话框(其代码如下)使用标准的是/否JOptionPaneThough this dialog is rather useless as written, its code is simple enough that you can use it as a template for more complex dialogs.虽然这个对话框在编写时相当无用,但它的代码非常简单,可以将其用作更复杂对话框的模板。

Besides setting the property change listener, the following code also calls the JDialog's setDefaultCloseOperation method and implements a window listener that handles the window close attempt properly. 除了设置属性更改监听器外,以下代码还调用JDialogsetDefaultCloseOperation方法,并实现一个窗口监听器,该监听器可以正确处理窗口关闭尝试。If you do not care to be notified when the user closes the window explicitly, then ignore the bold code.如果您不想在用户显式关闭窗口时收到通知,请忽略粗体代码。

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

final JDialog dialog = new JDialog(frame, 
                             "Click a button",
                             true);
dialog.setContentPane(optionPane);
dialog.setDefaultCloseOperation(
    JDialog.DO_NOTHING_ON_CLOSE);
dialog.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
        setLabel("Thwarted user attempt to close window.");
    }
});
optionPane.addPropertyChangeListener(
    new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            String prop = e.getPropertyName();

            if (dialog.isVisible() 
             && (e.getSource() == optionPane)
             && (prop.equals(JOptionPane.VALUE_PROPERTY))) {
                //If you were going to check something
                //before closing the window, you'd do
                //it here.
                dialog.setVisible(false);
            }
        }
    });
dialog.pack();
dialog.setVisible(true);

int value = ((Integer)optionPane.getValue()).intValue();
if (value == JOptionPane.YES_OPTION) {
    setLabel("Good.");
} else if (value == JOptionPane.NO_OPTION) {
    setLabel("Try using the window decorations "
             + "to close the non-auto-closing dialog. "
             + "You can't!");
}

The Dialog API对话API

The following tables list the commonly used JOptionPane and JDialog constructors and methods. 下表列出了常用的JOptionPaneJDialog构造函数和方法。Other methods you're likely to call are defined by the Dialog, Window and Component classes and include pack, setSize, and setVisible.您可能调用的其他方法由DialogWindowComponent类定义,包括packsetSizesetVisible

The API is listed as follows:API列表如下:

Showing Standard Modal Dialogs (Using JOptionPane Class Methods)显示标准模式对话框(使用JOptionPane类方法)
Method方法 Purpose目的
static void showMessageDialog(Component, Object)
static void showMessageDialog(Component, Object, String, int)
static void showMessageDialog(Component, Object, String, int, Icon)
Show a one-button, modal dialog that gives the user some information. 显示一个单键模式对话框,为用户提供一些信息。The arguments specify (in order) the parent component, message, title, message type, and icon for the dialog. 参数指定(按顺序)对话框的父组件、消息、标题、消息类型和图标。See Creating and Showing Simple Dialogs for a discussion of the arguments and their effects.有关参数及其效果的讨论,请参阅创建和显示简单对话框
static int showOptionDialog(Component, Object, String, int, int, Icon, Object[], Object) Show a customized modal dialog. 显示自定义模式对话框。The arguments specify (in order) the parent component, message, title, option type, message type, icon, options, and initial value for the dialog. 参数指定(按顺序)对话框的父组件、消息、标题、选项类型、消息类型、图标、选项和初始值。See Creating and Showing Simple Dialogs for a discussion of the arguments and their effects.有关参数及其效果的讨论,请参阅创建和显示简单对话框
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)
Show a modal dialog that asks the user a question. 显示询问用户问题的模式对话框。The arguments specify (in order) the parent component, message, title, option type, message type, and icon for the dialog. 参数指定(按顺序)对话框的父组件、消息、标题、选项类型、消息类型和图标。See Creating and Showing Simple Dialogs for a discussion of the arguments and their effects.有关参数及其效果的讨论,请参阅创建和显示简单对话框
static String showInputDialog(Object)
static String showInputDialog(Component, Object)
static String showInputDialog(Component, Object, String, int)
static String showInputDialog(Component, Object, String, int, Icon, Object[], Object)
Show a modal dialog that prompts the user for input. 显示提示用户输入的模式对话框。The single-argument version specifies just the message, with the parent component assumed to be null. 单参数版本仅指定消息,假设父组件为空。The arguments for the other versions specify (in order) the parent component, message, title, message type, icon, options, and initial value for the dialog. 其他版本的参数指定(按顺序)对话框的父组件、消息、标题、消息类型、图标、选项和初始值。See Creating and Showing Simple Dialogs for a discussion of the arguments and their effects.有关参数及其效果的讨论,请参阅创建和显示简单对话框
static void showInternalMessageDialog(...)
static void showInternalOptionDialog(...)
static void showInternalConfirmDialog(...)
static String showInternalInputDialog(...)
Implement a standard dialog as an internal frame. 将标准对话框实现为内部框架。See the JOptionPane API documentation for the exact list of arguments.有关参数的确切列表,请参阅JOptionPane API文档。
Methods for Using JOptionPanes Directly直接使用JOptionPane的方法
Method or Constructor方法或构造函数 Purpose目的
JOptionPane()
JOptionPane(Object)
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)
Creates a JOptionPane instance. 创建JOptionPane实例。See Creating and Showing Simple Dialogs for a discussion of the arguments and their effects.有关参数及其效果的讨论,请参阅创建和显示简单对话框
static Frame getFrameForComponent(Component)
static JDesktopPane getDesktopPaneForComponent(Component)
Handy JOptionPane class methods that find the frame or desktop pane, respectively, that the specified component is in.方便的JOptionPane类方法,分别查找指定组件所在的框架桌面窗格
int getMaxCharactersPerLineCount() Determines where line breaks will be automatically inserted in the option pane text. 确定将在选项窗格文本中自动插入换行符的位置。(The default is Integer.MAX_VALUE.) (默认值为Integer.MAX_VALUE。)To use this method, you must create a JOptionPane subclass. 要使用此方法,必须创建一个JOptionPane子类。For example, the following code results in an option pane with one word per line, due to the fact that each word in the string is 5 characters or less:例如,由于字符串中的每个单词不超过5个字符,以下代码导致选项窗格中每行有一个单词:
JOptionPane op = new JOptionPane("This is the text.") {
    public int getMaxCharactersPerLineCount() {
        return 5;
    }
};

Frequently Used JDialog Constructors and Methods常用的JDialog构造函数和方法
Method or Constructor方法或构造函数 Purpose目的
JDialog()
JDialog(Dialog)
JDialog(Dialog, boolean)
JDialog(Dialog, String)
JDialog(Dialog, String, boolean)
JDialog(Dialog, String, boolean, GraphicsConfiguration)
JDialog(Frame)
JDialog(Frame, boolean)
JDialog(Frame, String)
JDialog(Frame, String, boolean)
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, String title, Dialog.ModalityType modalityType, GraphicsConfiguration gc)
Creates a JDialog instance. 创建一个JDialog实例。The Frame argument, if any, is the frame (usually a JFrame object) that the dialog depends on. Frame参数(如果有)是对话框所依赖的框架(通常是JFrame对象)。Make the boolean argument true to specify a modal dialog, false or absent to specify a non-modal dialog. 将布尔参数设为true以指定模式对话框,将布尔参数设置为false或缺席以指定非模式对话框。You can also specify the title of the dialog, using a string argument.还可以使用字符串参数指定对话框的标题。
void setContentPane(Container)
Container getContentPane()
Get and set the content pane, which is usually the container of all the dialog's components. 获取并设置内容窗格,它通常是对话框所有组件的容器。See Using Top-Level Containers for more information.有关详细信息,请参阅使用顶级容器
void setDefaultCloseOperation(int)
int getDefaultCloseOperation()
Get and set what happens when the user tries to close the dialog. 获取并设置用户尝试关闭对话框时发生的情况。Possible values: DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE (the default). 可能的值:DISPOSE_ON_CLOSEDO_NOTHING_ON_CLOSEHIDE_ON_CLOSE(默认值)。See Responding to Window-Closing Events for more information.有关详细信息,请参阅响应窗口关闭事件
void setLocationRelativeTo(Component) Centers the dialog over the specified component.将对话框居中放置在指定的零部件上。
static void setDefaultLookAndFeelDecorated(boolean)
static boolean isDefaultLookAndFeelDecorated()
Set or get a hint as to whether the dialog's window decorations (such as borders, or widgets to close the window) should be provided by the current look and feel. 设置或获取对话框的窗口装饰(如边框或关闭窗口的小部件)是否应由当前外观提供的提示。Otherwise the dialog's decorations will be provided by the current window manager. 否则,对话框的装饰将由当前窗口管理器提供。See Specifying Window Decorations for more information.有关详细信息,请参阅指定窗口装饰

Examples that Use Dialogs使用对话框的示例

This table lists examples that use JOptionPane or JDialog. 下表列出了使用JOptionPaneJDialog的示例。To find other examples that use dialogs, see the example lists for progress bars, color choosers, and file choosers.要查找使用对话框的其他示例,请参阅进度条颜色选择器文件选择器的示例列表。

Example示例 Where Described描述位置 Notes备注
DialogDemo,
CustomDialog
This section本节 Creates many kinds of dialogs, using JOptionPane and JDialog.使用JOptionPaneJDialog创建多种对话框。
Framework Brings up a confirmation dialog when the user selects the Quit menu item.当用户选择退出菜单项时,将显示确认对话框。
ListDialog How to Use BoxLayout如何使用BoxLayout Implements a modal dialog containing a scrolling list and two buttons. 实现包含滚动列表和两个按钮的模式对话框。Does not use JOptionPane, except for the utility method getFrameForComponent.除了实用程序方法getFrameForComponent之外,不使用JOptionPane

Previous page: How to Use Combo Boxes
Next page: How to Use Editor Panes and Text Panes