Documentation

The Java™ Tutorials
Hide TOC
How to Make Frames (Main Windows)如何制作框架(主窗口)
Trail: Creating a GUI With Swing
Lesson: Using Swing Components
Section: How to Use Various Components

How to Make Frames (Main Windows)如何制作框架(主窗口)

A Frame is a top-level window with a title and a border. 框架是带有标题和边框的顶级窗口。The size of the frame includes any area designated for the border. 框架的大小包括为边界指定的任何区域。The dimensions of the border area may be obtained using the getInsets method. 可以使用getInsets方法获得边界区域的尺寸。Since the border area is included in the overall size of the frame, the border effectively obscures a portion of the frame, constraining the area available for rendering and/or displaying subcomponents to the rectangle which has an upper-left corner location of (insets.left, insets.top), and has a size of width - (insets.left + insets.right) by height - (insets.top + insets.bottom).由于边框区域包含在框架的整体大小中,因此边框有效地遮挡了框架的一部分,将可用于渲染和/或显示子组件的区域限制为矩形,该矩形的左上角位置为(insets.left, insets.top),且其大小为width - (insets.left + insets.right)乘以height - (insets.top + insets.bottom)

A frame, implemented as an instance of the JFrame class, is a window that has decorations such as a border, a title, and supports button components that close or iconify the window. 框架实现为JFrame类的一个实例,是一个具有边框、标题等装饰的窗口,并支持关闭或图标化窗口的按钮组件。Applications with a GUI usually include at least one frame. 具有GUI的应用程序通常至少包括一个框架。Applets sometimes use frames, as well.小程序有时也使用框架。

To make a window that is dependent on another window — disappearing when the other window is iconified, for example — use a dialog instead of frame.. 以使窗口依赖于另一窗口—当另一个窗口被图标化时消失— 使用dialog而不是frameTo make a window that appears within another window, use an internal frame. 要使窗口显示在另一个窗口中,请使用内部框架

Creating and Showing Frames创建和显示框架

Here is a picture of the extremely plain window created by the FrameDemo demonstration application. 下面是FrameDemo演示应用程序创建的极其简单的窗口的图片。You can find the source code in FrameDemo.java. 您可以在FrameDemo.java中找到源代码。You can run FrameDemo ( download JDK 7 or later).您可以运行FrameDemo下载JDK 7或更高版本)。

A very boring frame

The following FrameDemo code shows how to create and set up a frame.下面的FrameDemo代码展示了如何创建和设置框架。


//1. Create the frame.
JFrame frame = new JFrame("FrameDemo");

//2. Optional: What happens when the frame closes?
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//3. Create components and put them in the frame.
//...create emptyLabel...
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);

//4. Size the frame.
frame.pack();

//5. Show it.
frame.setVisible(true);

Here are some details about the code:以下是代码的一些详细信息:

  1. The first line of code creates a frame using a constructor that lets you set the frame title. 第一行代码使用构造函数创建一个框架,该构造函数允许您设置框架标题。The other frequently used JFrame constructor is the no-argument constructor.另一个常用的JFrame构造函数是无参数构造函数。
  2. Next the code specifies what happens when your user closes the frame. 接下来,代码指定用户关闭框架时发生的情况。The EXIT_ON_CLOSE operation exits the program when your user closes the frame. 当用户关闭框架时,EXIT_ON_CLOSE操作退出程序。This behavior is appropriate for this program because the program has only one frame, and closing the frame makes the program useless. 此行为适用于此程序,因为该程序只有一个帧,关闭该帧会使程序无用。

    See Responding to Window-Closing Events for more information.有关详细信息,请参阅响应窗口关闭事件

  3. The next bit of code adds a blank label to the frame content pane. 下一位代码将为框架内容窗格添加一个空白标签。If you're not already familiar with content panes and how to add components to them, please read Adding Components to the Content Pane. 如果您还不熟悉内容窗格以及如何向其中添加组件,请阅读将组件添加到内容窗格

    For frames that have menus, you'd typically add the menu bar to the frame here using the setJMenuBar method. 对于具有菜单的框架,通常使用setJMenuBar方法将菜单栏添加到框架中。See How to Use Menus for details.有关详细信息,请参阅如何使用菜单

  4. The pack method sizes the frame so that all its contents are at or above their preferred sizes. pack方法确定框架的尺寸,使其所有内容物处于或高于其优选尺寸。An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). pack的另一种方法是通过调用setSizesetBounds(也设置帧位置)显式地建立帧大小。In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size. 一般来说,使用pack比调用setSize更可取,因为pack让框架布局管理器负责框架大小,布局管理器擅长调整平台依赖性和其他影响组件大小的因素。

    This example does not set the frame location, but it is easy to do so using either the setLocationRelativeTo or setLocation method. For example, the following code centers a frame onscreen:本例不设置帧位置,但使用setLocationRelativeTosetLocation方法很容易设置。例如,以下代码在屏幕上居中显示帧:

    frame.setLocationRelativeTo(null);
  5. Calling setVisible(true) makes the frame appear onscreen. 调用setVisible(true)将使帧显示在屏幕上。Sometimes you might see the show method used instead. 有时您可能会看到改用show方法。The two usages are equivalent, but we use setVisible(true) for consistency's sake.这两种用法是等价的,但为了一致性,我们使用setVisible(true)

Specifying Window Decorations指定窗口装饰

By default, window decorations are supplied by the native window system. 默认情况下,窗口装饰由本机窗口系统提供。However, you can request that the look-and-feel provide the decorations for a frame. 但是,您可以要求外观为框架提供装饰。You can also specify that the frame have no window decorations at all, a feature that can be used on its own, or to provide your own decorations, or with full-screen exclusive mode.您还可以指定框架完全没有窗口装饰,该功能可以单独使用,也可以提供您自己的装饰,或者使用全屏独占模式

Besides specifying who provides the window decorations, you can also specify which icon is used to represent the window. 除了指定谁提供窗口装饰外,还可以指定哪个图标用于表示窗口。Exactly how this icon is used depends on the window system or look and feel that provides the window decorations. 该图标的具体使用方式取决于提供窗口装饰的窗口系统或外观。If the window system supports minimization, then the icon is used to represent the minimized window. 如果窗口系统支持最小化,则图标用于表示最小化窗口。Most window systems or look and feels also display the icon in the window decorations. 大多数窗口系统或外观也在窗口装饰中显示图标。A typical icon size is 16x16 pixels, but some window systems use other sizes.典型的图标大小为16x16像素,但某些窗口系统使用其他大小。

The following snapshots show three frames that are identical except for their window decorations. 下面的快照显示了三个相同的框架,除了它们的窗口装饰。As you can tell by the appearance of the button in each frame, all three use the Java look and feel. 从每个帧中按钮的外观可以看出,所有三个都使用Java外观。The first uses decorations provided by the window system, which happen to be Microsoft Windows, but could as easily be any other system running the Java platform.第一种使用窗口系统提供的装饰,该系统恰好是Microsoft Windows,但也可以是运行Java平台的任何其他系统。The second and third use window decorations provided by the Java look and feel. 第二个和第三个使用Java外观提供的窗口装饰。The third frame uses Java look and feel window decorations, but has a custom icon. 第三个框架使用Java外观窗口装饰,但有一个自定义图标。

A frame with decorations provided by the window system A frame with decorations provided by the look and feel A frame with a custom icon
Window decorations provided by the look and feel由外观和感觉提供的窗口装饰 Window decorations provided by the window system窗口系统提供的窗口装饰 Custom icon; window decorations provided by the look and feel自定义图标;由外观和感觉提供的窗口装饰

Here is an example of creating a frame with a custom icon and with window decorations provided by the look and feel:下面是一个创建带有自定义图标的框架的示例,以及由“外观和感觉”提供的窗口装饰:

//Ask for window decorations provided by the look and feel.
JFrame.setDefaultLookAndFeelDecorated(true);

//Create the frame.
JFrame frame = new JFrame("A window");

//Set the frame icon to an image loaded from a file.
frame.setIconImage(new ImageIcon(imgURL).getImage());

As the preceding code snippet implies, you must invoke the setDefaultLookAndFeelDecorated method before creating the frame whose decorations you wish to affect. 正如前面的代码片段所暗示的,在创建要影响其装饰的框架之前,必须调用setDefaultLookAndFeelDecorated方法。The value you set with setDefaultLookAndFeelDecorated is used for all subsequently created JFrames. 使用setDefaultLookAndFeelDecorated设置的值将用于所有随后创建的JFrameYou can switch back to using window system decorations by invoking JFrame.setDefaultLookAndFeelDecorated(false). 通过调用JFrame.setDefaultLookAndFeelDecorated(false),可以切换回使用窗口系统装饰。Some look and feels might not support window decorations; in this case, the window system decorations are used.一些外观和感觉可能不支持窗口装饰;在这种情况下,使用窗系统装饰。

The full source code for the application that creates the frames pictured above is in FrameDemo2.java. 创建上述框架的应用程序的完整源代码位于FrameDemo2.java中。Besides showing how to choose window decorations, FrameDemo2 also shows how to disable all window decorations and gives an example of positioning windows. 除了展示如何选择窗口装饰外,FrameDemo2还展示了如何禁用所有窗口装饰,并给出了一个定位窗口的示例。It includes two methods that create the Image objects used as icons — one is loaded from a file, and the other is painted from scratch. 它包括创建用作图标的Image对象的两种方法;一个从文件加载,另一个从头开始绘制。


Try this:: 
  1. Click the Launch button to run the Frame 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 FrameDemo2 example

  2. Bring up two windows, both with look-and-feel-provided decorations, but with different icons.打开两个窗口,都有外观和感觉提供的装饰,但有不同的图标。
    The Java look and feel displays the icons in its window decorations. Java外观在其窗口装饰中显示图标。Depending on your window system, the icon may be used elsewhere to represent the window, especially when the window is minimized.根据您的窗口系统,图标可以在其他地方用于表示窗口,尤其是当窗口最小化时。
  3. Bring up one or more windows with window system decorations.打开一个或多个带有窗口系统装饰的窗口。
    See if your window system treats these icons differently.查看您的窗口系统是否以不同方式对待这些图标。
  4. Bring up one or more windows with no window decorations.打开一个或多个没有窗户装饰的窗户。
    Play with the various types of windows to see how the window decorations, window system, and frame icons interact.玩各种类型的窗口,看看窗口装饰、窗口系统和框架图标是如何交互的。

Responding to Window-Closing Events响应窗口关闭事件

By default, when the user closes a frame onscreen, the frame is hidden. 默认情况下,当用户关闭屏幕上的帧时,该帧将被隐藏。Although invisible, the frame still exists and the program can make it visible again. 虽然不可见,但框架仍然存在,程序可以使其再次可见。If you want different behavior, then you need to either register a window listener that handles window-closing events, or you need to specify default close behavior using the setDefaultCloseOperation method. 如果需要不同的行为,则需要注册处理窗口关闭事件的窗口侦听器,或者需要使用setDefaultCloseOperation方法指定默认关闭行为。You can even do both.你甚至可以同时做这两件事。

The argument to setDefaultCloseOperation must be one of the following values, the first three of which are defined in the WindowConstants interface (implemented by JFrame, JInternalPane, and JDialog):setDefaultCloseOperation的参数必须是以下值之一,前三个值在WindowConstants接口中定义(由JFrameJInternalPaneJDialog实现):

DO_NOTHING_ON_CLOSE
Do not do anything when the user requests that the window close. 当用户请求关闭窗口时,不要执行任何操作。Instead, the program should probably use a window listener that performs some other action in its windowClosing method.相反,程序可能应该使用一个窗口侦听器,在其windowClosing方法中执行一些其他操作。
HIDE_ON_CLOSE (the default for JDialog and JFrame)JDialogJFrame的默认值)
Hide the window when the user closes it. 用户关闭窗口时隐藏窗口。This removes the window from the screen but leaves it displayable.这将从屏幕上删除窗口,但使其可显示。
DISPOSE_ON_CLOSE (the default for JInternalFrame)JInternalFrame的默认值)
Hide and dispose of the window when the user closes it. 当用户关闭窗口时隐藏并处理该窗口。This removes the window from the screen and frees up any resources used by it.这将从屏幕上删除窗口并释放其使用的所有资源。
EXIT_ON_CLOSE (defined in the JFrame class)(在JFrame类中定义)
Exit the application, using System.exit(0). 使用System.exit(0)退出应用程序。This is recommended for applications only. 建议仅用于应用程序。If used within an applet, a SecurityException may be thrown.如果在小程序中使用,可能会引发SecurityException


Note: 

DISPOSE_ON_CLOSE can have results similar to EXIT_ON_CLOSE if only one window is onscreen. 如果屏幕上只有一个窗口,DISPOSE_ON_CLOSE可能会产生类似于EXIT_ON_CLOSE的结果。More precisely, when the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate. 更准确地说,当Java虚拟机(VM)内的最后一个可显示窗口被丢弃时,VM可以终止。See AWT Threading Issues for details.有关详细信息,请参阅AWT线程问题


The default close operation is executed after any window listeners handle the window-closing event. 默认关闭操作在任何窗口侦听器处理窗口关闭事件后执行。So, for example, assume that you specify that the default close operation is to dispose of a frame. 因此,例如,假设您指定默认的关闭操作是处理帧。You also implement a window listener that tests whether the frame is the last one visible and, if so, saves some data and exits the application. 您还实现了一个窗口监听器,用于测试框架是否是最后一个可见的,如果是,则保存一些数据并退出应用程序。Under these conditions, when the user closes a frame, the window listener will be called first. 在这些情况下,当用户关闭帧时,将首先调用窗口侦听器。If it does not exit the application, then the default close operation — disposing of the frame — will then be performed.如果不退出应用程序,则默认关闭操作—设置框架—然后将执行。

For more information about handling window-closing events, see How to Write Window Listeners. 有关处理窗口关闭事件的详细信息,请参阅如何编写窗口侦听器Besides handling window-closing events, window listeners can also react to other window state changes, such as iconification and activation.除了处理窗口关闭事件外,窗口侦听器还可以对其他窗口状态更改做出反应,如图标化和激活。

The Frame API

The following tables list the commonly used JFrame constructors and methods. 下表列出了常用的JFrame构造函数和方法。Other methods you might want to call are defined by the java.awt.Frame, java.awt.Window, and java.awt.Component classes, from which JFrame descends.您可能需要调用的其他方法由java.awt.Framejava.awt.Windowjava.awt.Component类定义,JFrame从这些类派生。

Because each JFrame object has a root pane, frames have support for interposing input and painting behavior in front of the frame children, placing children on different "layers", and for Swing menu bars. 因为每个JFrame对象都有一个根窗格,所以框架支持在框架子对象前面插入输入和绘制行为,将子对象放置在不同的“层”上,并支持Swing菜单栏。These topics are introduced in Using Top-Level Containers and explained in detail in How to Use Root Panes.这些主题在使用顶级容器中介绍,并在如何使用根窗格中详细解释。

The API for using frames falls into these categories:使用框架的API分为以下几类:

Creating and Setting Up a Frame创建和设置框架
Method or Constructor方法或构造函数 Purpose目的
JFrame()
JFrame(String)
Create a frame that is initially invisible. 创建一个最初不可见的帧。The String argument provides a title for the frame. String参数提供框架的标题。To make the frame visible, invoke setVisible(true) on it.要使框架可见,请在其上调用setVisible(true)
void setDefaultCloseOperation(int)
int getDefaultCloseOperation()
Set or get the operation that occurs when the user pushes the close button on this frame. Possible choices are:设置或获取用户按下此框架上的关闭按钮时发生的操作。可能的选择是:
  • DO_NOTHING_ON_CLOSE
  • HIDE_ON_CLOSE
  • DISPOSE_ON_CLOSE
  • EXIT_ON_CLOSE
The first three constants are defined in the WindowConstants interface, which JFrame implements. 前三个常量在WindowConstants接口中定义,JFrame实现了该接口。The EXIT_ON_CLOSE constant is defined in the JFrame class.EXIT_ON_CLOSE常量在JFrame类中定义。
void setIconImage(Image)
Image getIconImage()
(in Frame)
Set or get the icon that represents the frame. 设置或获取表示框架的图标。Note that the argument is a java.awt.Image object, not a javax.swing.ImageIcon (or any other javax.swing.Icon implementation).请注意,该参数是一个java.awt.Image对象,而不是javax.swing.ImageIcon(或任何其他javax.swing.Icon实现)。
void setTitle(String)
String getTitle()
(in Frame)
Set or get the frame title.设置或获取框架标题。
void setUndecorated(boolean)
boolean isUndecorated()
(in Frame)
Set or get whether this frame should be decorated. 设置或获取是否应装饰此框架。Works only if the frame is not yet displayable (has not been packed or shown). 仅当帧尚不可显示(尚未打包或显示)时有效。Typically used with full-screen exclusive mode or to enable custom window decorations.通常用于全屏独占模式或启用自定义窗口装饰。
static void setDefaultLookAndFeelDecorated(boolean)
static boolean isDefaultLookAndFeelDecorated()
Determine whether subsequently created JFrames should have their Window decorations (such as borders, and widgets for closing the window) provided by the current look-and-feel. 确定随后创建的JFrame是否应具有当前外观提供的窗口装饰(如边框和用于关闭窗口的小部件)。Note that this is only a hint, as some look and feels may not support this feature.请注意,这只是一个提示,因为某些外观可能不支持此功能。
Setting the Window Size and Location设置窗口大小和位置
Method方法 Purpose目的
void pack()
(in Window)
Size the window so that all its contents are at or above their preferred sizes.调整窗口大小,使其所有内容处于或高于其首选大小。
void setSize(int, int)
void setSize(Dimension)
Dimension getSize()
(in Component)
Set or get the total size of the window. 设置或获取窗口的总大小。The integer arguments to setSize specify the width and height, respectively.setSize的整数参数分别指定宽度和高度。
void setBounds(int, int, int, int)
void setBounds(Rectangle)
Rectangle getBounds()
(in Component)
Set or get the size and position of the window. 设置或获取窗口的大小和位置。For the integer version of setBounds, the window upper left corner is at the x, y location specified by the first two arguments, and has the width and height specified by the last two arguments.对于整数版本的setBounds,窗口左上角位于前两个参数指定的x, y位置,并具有后两个参数所指定的宽度和高度。
void setLocation(int, int)
Point getLocation()
(in Component)
Set or get the location of the upper left corner of the window. 设置或获取窗口左上角的位置。The parameters are the x and y values, respectively.参数分别是xy值。
void setLocationRelativeTo(Component)
(in Window)
Position the window so that it is centered over the specified component. 定位窗口,使其位于指定构件的中心。If the argument is null, the window is centered onscreen. 如果参数为null,则窗口在屏幕上居中。To properly center the window, you should invoke this method after the window size has been set.要正确居中窗口,应在设置窗口大小后调用此方法。
Methods Related to the Root Pane与根窗格相关的方法
Method方法 Purpose目的
void setContentPane(Container)
Container getContentPane()
Set or get the frame content pane. 设置或获取框架内容窗格。The content pane contains the visible GUI components within the frame.内容窗格包含框架内的可见GUI组件。
JRootPane createRootPane()
void setRootPane(JRootPane)
JRootPane getRootPane()
Create, set, or get the frame root pane. 创建、设置或获取框架根窗格。The root pane manages the interior of the frame including the content pane, the glass pane, and so on.根窗格管理框架的内部,包括内容窗格、玻璃窗格等。
void setJMenuBar(JMenuBar)
JMenuBar getJMenuBar()
Set or get the frame menu bar to manage a set of menus for the frame.设置或获取框架菜单栏以管理框架的一组菜单。
void setGlassPane(Component)
Component getGlassPane()
Set or get the frame glass pane. 设置或获取框架玻璃窗格。You can use the glass pane to intercept mouse events or paint on top of your program GUI.您可以使用玻璃窗格拦截鼠标事件或在程序GUI顶部绘制。
void setLayeredPane(JLayeredPane)
JLayeredPane getLayeredPane()
Set or get the frame layered pane. 设置或获取框架分层窗格。You can use the frame layered pane to put components on top of or behind other components.您可以使用框架分层窗格将组件放置在其他组件的顶部或后面。

Examples that Use Frames使用框架的示例

All of the standalone applications in this trail use JFrame. 本教程中的所有独立应用程序都使用JFrameThe following table lists a few and tells you where each is discussed.下表列出了一些,并告诉您每个讨论的位置。

Example示例 Where Described描述位置 Notes备注
FrameDemo The Example Explained示例说明 Displays a basic frame with one component.显示包含一个组件的基本框架。
FrameDemo2 Specifying Window Decorations指定窗口装饰 Lets you create frames with various window decorations.用于创建具有各种窗口装饰的框架。
Framework A study in creating and destroying windows, in implementing a menu bar, and in exiting an application.创建和销毁窗口、实现菜单栏和退出应用程序的研究。
LayeredPaneDemo How to Use Layered Panes如何使用分层窗格 Illustrates how to use a layered pane (but not the frame layered pane).说明如何使用分层窗格(但不是框架分层窗格)。
GlassPaneDemo The Glass Pane玻璃窗格 Illustrates the use of a frame glass pane.说明了框架玻璃窗格的使用。
MenuDemo How to Use Menus如何使用菜单 Shows how to put a JMenuBar in a JFrame.演示如何将JMenuBar放在JFrame中。

Previous page: How to Use Formatted Text Fields
Next page: How to Use Internal Frames