Documentation

The Java™ Tutorials
Hide TOC
How to Use Labels如何使用标签
Trail: Creating a GUI With Swing
Lesson: Using Swing Components
Section: How to Use Various Components

How to Use Labels如何使用标签

With the JLabel class, you can display unselectable text and images. 使用JLabel类,可以显示不可选择的文本和图像。If you need to create a component that displays a string, an image, or both, you can do so by using or extending JLabel. 如果需要创建一个显示字符串、图像或两者的组件,可以使用或扩展JLabelIf the component is interactive and has a certain state, use a button instead of a label.如果组件是交互式的并且具有特定状态,则使用按钮而不是标签。

By specifying HTML code in a label's text, you can give the label various characteristics such as multiple lines, multiple fonts or multiple colors. 通过在标签的文本中指定HTML代码,可以为标签提供各种特性,如多行、多字体或多种颜色。If the label uses just a single color or font, you can avoid the overhead of HTML processing by using the setForeground or setFont method instead. 如果标签仅使用单一颜色或字体,则可以使用setForegroundsetFont方法来避免HTML处理的开销。See Using HTML in Swing Components for details.有关详细信息,请参阅在Swing组件中使用HTML

Note that labels are not opaque by default. 请注意,默认情况下标签不是不透明的。If you need to paint the label's background, it is recommended that you turn its opacity property to "true". 如果需要绘制标签的背景,建议将其不透明度属性设置为“true”。The following code snippet shows how to do this.下面的代码片段显示了如何做到这一点。

label.setOpaque(true);

The following picture introduces an application that displays three labels. 下图介绍了一个显示三个标签的应用程序。The window is divided into three rows of equal height; the label in each row is as wide as possible.窗口分为三行,高度相等;每行中的标签尽可能宽。

A snapshot of LabelDemo, which uses labels with text and icons.

Try this: 
  1. Click the Launch button to run the Label 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 LabelDemo Application
  2. Resize the window so you can see how the labels' contents are placed within the labels' drawing area.调整窗口大小,以便您可以看到标签的内容如何放置在标签的绘图区域中。
    All the label contents have default vertical alignment — that is, the label contents are centered vertically in the label's drawing area. 所有标签内容都具有默认的垂直对齐;也就是说,标签内容在标签的绘图区域中垂直居中。The top label, which contains both an image and text, has horizontal center alignment. 包含图像和文本的顶部标签具有水平居中对齐。The second label, which contains just text, has left (leading) alignment, which is the default for text-only labels in left-to-right languages. 第二个标签(仅包含文本)具有左(前导)对齐方式,这是从左到右语言中纯文本标签的默认对齐方式。The third label, which contains just an image, has horizontal center alignment, which is the default for image-only labels.第三个标签仅包含图像,具有水平中心对齐,这是仅图像标签的默认设置。

Below is the code from LabelDemo.java that creates the labels in the previous example.下面是LabelDemo.java中的代码,用于创建前面示例中的标签。

ImageIcon icon = createImageIcon("images/middle.gif");
. . .
label1 = new JLabel("Image and Text",
                    icon,
                    JLabel.CENTER);
//Set the position of the text, relative to the icon:
label1.setVerticalTextPosition(JLabel.BOTTOM);
label1.setHorizontalTextPosition(JLabel.CENTER);

label2 = new JLabel("Text-Only Label");
label3 = new JLabel(icon);

The code for the createImageIcon method is similar to that used throughout this tutorial. createImageIcon方法的代码与本教程中使用的代码类似。You can find it in How to Use Icons.您可以在如何使用图标中找到它。

Often, a label describes another component. 通常,标签描述另一个组件。When this occurs, you can improve your program's accessibility by using the setLabelFor method to identify the component that the label describes. 发生这种情况时,可以通过使用setLabelFor方法来标识标签描述的组件,从而提高程序的可访问性。For example:例如:

amountLabel.setLabelFor(amountField);

The preceding code, taken from the FormattedTextFieldDemo example discussed in How to Use Formatted Text Fields, lets assistive technologies know that the label (amountLabel) provides information about the formatted text field (amountField). 前面的代码取自如何使用格式化文本字段中讨论的FormattedTextFieldDemo示例,它让辅助技术知道标签(amountLabel)提供了有关格式化文本字段(amountField)的信息。For more information about assistive technologies, see How to Support Assistive Technologies.有关辅助技术的更多信息,请参阅如何支持辅助技术

The Label API

The following tables list the commonly used JLabel constructors and methods. 下表列出了常用的JLabel构造函数和方法。Other methods you are likely to call are defined by the Component and JComponent classes. 您可能调用的其他方法由ComponentJComponent类定义。They include setFont, setForeground, setBorder, setOpaque, and setBackground. 它们包括setFontsetForegroundsetBordersetOpaquesetBackgroundSee The JComponent Class for details. 有关详细信息,请参阅JComponent类。The API for using labels falls into three categories:使用标签的API分为三类:


Note: 

In the following API, do not confuse label alignment with X and Y alignment. 在以下API中,不要将标签对齐与X和Y对齐混淆。X and Y alignment are used by layout managers and can affect the way any component — not just a label — is sized or positioned. 布局管理器使用X和Y对齐,并且可以影响任何组件的方式;不仅仅是标签—确定尺寸或定位。Label alignment, on the other hand, has no effect on a label's size or position. 另一方面,标签对齐对标签的大小或位置没有影响。Label alignment simply determines where, inside the label's painting area, the label's contents are positioned. 标签对齐仅确定标签内容在标签的绘制区域内的位置。Typically, the label's painting area is exactly the size needed to paint on the label and thus label alignment is irrelevant. 通常,标签的绘制区域正好是在标签上绘制所需的大小,因此标签对齐不相关。For more information about X and Y alignment, see How to Use BoxLayout.有关X和Y对齐的更多信息,请参阅如何使用BoxLayout


Setting or Getting the Label's Contents设置或获取标签内容
Method or Constructor方法或构造函数 Purpose意图
JLabel(Icon)
JLabel(Icon, int)
JLabel(String)
JLabel(String, Icon, int)
JLabel(String, int)
JLabel()
Creates a JLabel instance, initializing it to have the specified text/image/alignment. 创建一个JLabel实例,并将其初始化为具有指定的文本/图像/对齐方式。The int argument specifies the horizontal alignment of the label's contents within its drawing area. int参数指定标签内容在其绘图区域内的水平对齐方式。The horizontal alignment must be one of the following constants defined in the SwingConstants interface (which JLabel implements): LEFT, CENTER, RIGHT, LEADING, or TRAILING. 水平对齐必须是SwingConstants接口(JLabel实现)中定义的以下常量之一:LEFTCENTERRIGHTLEADINGTRAILINGFor ease of localization, we strongly recommend using LEADING and TRAILING, rather than LEFT and RIGHT.为了便于本地化,我们强烈建议使用LEADINGTRAILING,而不是LEFTRIGHT
void setText(String)
String getText()
Sets or gets the text displayed by the label. 设置或获取标签显示的文本。You can use HTML tags to format the text, as described in Using HTML in Swing Components.您可以使用HTML标记来格式化文本,如在Swing组件中使用HTML中所述。
void setIcon(Icon)
Icon getIcon()
Sets or gets the image displayed by the label.设置或获取标签显示的图像。
void setDisplayedMnemonic(char)
char getDisplayedMnemonic()
Sets or gets the letter that should look like a keyboard alternative. 设置或获取看起来像键盘替代项的字母。This is helpful when a label describes a component (such as a text field) that has a keyboard alternative but cannot display it. 当标签描述了一个组件(如文本字段)时,如果该组件具有键盘选项,但无法显示,这将非常有用。If the labelFor property is also set (using setLabelFor), then when the user activates the mnemonic, the keyboard focus is transferred to the component specified by the labelFor property.如果还设置了labelFor属性(使用setLabelFor),则当用户激活助记符时,键盘焦点将转移到labelFor属性指定的组件。
void setDisplayedMnemonicIndex(int)
int getDisplayedMnemonicIndex()
Sets or gets a hint as to which character in the text should be decorated to represent the mnemonic. 设置或获取关于文本中哪个字符应被修饰以表示助记符的提示。This is useful when you have two instances of the same character and wish to decorate the second instance. 当您有两个相同角色的实例并希望装饰第二个实例时,这非常有用。For example, setDisplayedMnemonicIndex(5) decorates the character that is at position 5 (that is, the 6th character in the text). 例如,setDisplayedNemonicIndex(5)修饰位于位置5的字符(即文本中的第6个字符)。Not all types of look and feel may support this feature.并非所有类型的外观都支持此功能。
void setDisabledIcon(Icon)
Icon getDisabledIcon()
Sets or gets the image displayed by the label when it is disabled. 设置或获取标签禁用时显示的图像。If you do not specify a disabled image, then the look and feel creates one by manipulating the default image.如果未指定禁用的图像,则外观将通过操纵默认图像创建一个图像。
Fine Tuning the Label's Appearance微调标签的外观
Method方法 Purpose目的
void setHorizontalAlignment(int)
void setVerticalAlignment(int)
int getHorizontalAlignment()
int getVerticalAlignment()
Sets or gets the area on the label where its contents should be placed. 设置或获取标签上应放置其内容的区域。The SwingConstants interface defines five possible values for horizontal alignment: LEFT, CENTER (the default for image-only labels), RIGHT, LEADING (the default for text-only labels), TRAILING. 接口为水平对齐定义了五个可能的值:LEFTCENTER(仅图像标签的默认值)、RIGHTLEADING(仅文本标签的默认)、TRAILINGFor vertical alignment: TOP, CENTER (the default), and BOTTOM.SwingConstants对于垂直对齐:TOPCENTER(默认值)和BOTTOM
void setHorizontalTextPosition(int)
void setVerticalTextPosition(int)
int getHorizontalTextPosition()
int getVerticalTextPosition()
Sets or gets the location where the label's text will be placed, relative to the label's image. 设置或获取标签文本相对于标签图像的放置位置。The SwingConstants interface defines five possible values for horizontal position: LEADING, LEFT, CENTER, RIGHT, and TRAILING (the default). SwingConstants接口为水平位置定义了五个可能的值:LEADINGLEFTCENTERRIGHTTRAILING(默认值)。For vertical position: TOP, CENTER (the default), and BOTTOM.对于垂直位置:TOPCENTER(默认值)和BOTTOM
void setIconTextGap(int)
int getIconTextGap()
Sets or gets the number of pixels between the label's text and its image.设置或获取标签文本与其图像之间的像素数。
Supporting Accessibility支持无障碍
Method方法 Purpose目的
void setLabelFor(Component)
Component getLabelFor()
Sets or gets which component the label describes.设置或获取标签描述的组件。

Examples That Use Labels使用标签的示例

The following table lists some of the many examples that use labels.下表列出了许多使用标签的示例。

Example示例 Where Described描述位置 Notes备注
LabelDemo This section本节 Shows how to specify horizontal and vertical alignment as well as how to align a label's text and image.显示如何指定水平和垂直对齐,以及如何对齐标签的文本和图像。
HtmlDemo Using HTML in Swing Components在Swing组件中使用HTML Lets you experiment with specifying HTML text for a label.允许您尝试为标签指定HTML文本。
BoxAlignmentDemo Fixing Alignment Problems修复对齐问题 Demonstrates possible alignment problems when using a label in a vertical box layout. 演示在垂直框布局中使用标签时可能出现的对齐问题。Shows how to solve the problem.显示如何解决问题。
DialogDemo How to Use Dialogs如何使用对话框 Uses a changeable label to display instructions and provide feedback.使用可更改标签显示说明并提供反馈。
SplitPaneDemo How to Use Split Panes and How to Use Lists如何使用拆分窗格如何使用列表 Displays an image using a label inside of a scroll pane.使用滚动窗格内的标签显示图像。
SliderDemo2 How to Use Sliders如何使用滑块 Uses JLabel to provide labels for a slider.使用JLabel为滑块提供标签。
TableDialogEditDemo How to Use Tables如何使用表格 Implements a label subclass, ColorRenderer, to display colors in table cells.实现标签子类ColorRenderer,以在表单元格中显示颜色。
FormattedTextFieldDemo How to Use Formatted Text Fields如何使用格式化文本字段 Has four rows, each containing a label and the formatted text field it describes.有四行,每行包含一个标签及其描述的格式化文本字段。
TextComponentDemo Text Component Features文本组件功能 TextComponentDemo has an inner class (CaretListenerLabel) that extends JLabel to provide a label that listens for events, updating itself based on the events.具有一个内部类(CaretListenerLabel),该类扩展JLabel以提供一个监听事件的标签,并根据事件更新自身。
ColorChooserDemo How to Use Color Choosers如何使用颜色选择器 Uses an opaque label to display the currently chosen color against a fixed-color background.使用不透明标签以固定颜色背景显示当前选定的颜色。

See the Using JavaFX UI Controls: Label tutorial to learn about JavaFX labeled controls.请参阅使用JavaFXUI控件:标签教程以了解JavaFX标签控件


Previous page: How to Use Internal Frames
Next page: How to Use Layered Panes