Documentation

The Java™ Tutorials
Hide TOC
How to Use Borders如何使用边框
Trail: Creating a GUI With Swing
Lesson: Using Swing Components

How to Use Borders如何使用边框

Every JComponent can have one or more borders. 每个JComponent都可以有一个或多个边界。Borders are incredibly useful objects that, while not themselves components, know how to draw the edges of Swing components. 边界是非常有用的对象,虽然它本身不是组件,但知道如何绘制Swing组件的边。Borders are useful not only for drawing lines and fancy edges, but also for providing titles and empty space around components.边框不仅可用于绘制线条和花哨的边缘,还可用于在组件周围提供标题和空白空间。


Note: 

Our examples set borders on JPanels, JLabels, and custom subclasses of JComponent. 示例设置了JPanelJLabelJComponent的自定义子类的边界。Although technically you can set the border on any object that inherits from JComponent, the look and feel implementation of many standard Swing components doesn't work well with user-set borders. 虽然从技术上讲,您可以在继承自JComponent的任何对象上设置边界,但许多标准Swing组件的外观实现与用户设置边界并不兼容。In general, when you want to set a border on a standard Swing component other than JPanel or JLabel, we recommend that you put the component in a JPanel and set the border on the JPanel.通常,当您想在除JPanelJLabel之外的标准Swing组件上设置边框时,我们建议您将组件放在JPanel中,并在JPannel上设置边框。


To put a border around a JComponent, you use its setBorder method. 要在JComponent周围放置边框,可以使用其setBorder方法。You can use the BorderFactory class to create most of the borders that Swing provides. 您可以使用BorderFactory类创建Swing提供的大多数边界。If you need a reference to a border — say, because you want to use it in multiple components — you can save it in a variable of type Border. 如果需要对边框的引用—例如,因为您想在多个组件中使用它—可以将其保存在Border类型的变量中。Here is an example of code that creates a bordered container:以下是创建带边框容器的代码示例:

JPanel pane = new JPanel();
pane.setBorder(BorderFactory.createLineBorder(Color.black));

Here's a picture of the container, which contains a label component. 这是容器的图片,其中包含标签组件。The black line drawn by the border marks the edge of the container.由边框绘制的黑线标记容器的边缘。

A line border

The rest of this page discusses the following topics:本页其余部分讨论以下主题:

The BorderDemo ExampleBorderDemo示例

The following pictures show an application called BorderDemo that displays the borders Swing provides. 下图显示了一个名为BorderDemo的应用程序,它显示了Swing提供的边界。We show the code for creating these borders a little later, in Using the Borders Provided by Swing.稍后,我们在使用Swing提供的边框中展示了创建这些边界的代码。

Click the Launch button to run the BorderDemo example using Java™ Web Start (download JDK 7 or later). 单击Launch按钮,使用Java™Web启动运行BorderDemo示例(下载JDK 7或更高版本)。Alternatively, to compile and run the example yourself, consult the example index.或者,要自己编译和运行示例,请参考示例索引

Launches the BorderDemo example
BorderDemo: Simple Borders

The next picture shows some matte borders. 下图显示了一些哑光边框。When creating a matte border, you specify how many pixels it occupies at the top, left, bottom, and right of a component. 创建蒙版边框时,可以指定它在组件的顶部、左侧、底部和右侧占据的像素数。You then specify either a color or an icon for the matte border to draw. 然后指定要绘制的无光边框的颜色或图标。You need to be careful when choosing the icon and determining your component's size; otherwise, the icon might get chopped off or have mismatch at the component's corners.在选择图标和确定组件大小时,您需要小心;否则,该图标可能会被切掉或在组件的角处不匹配。

BorderDemo: Matte Borders

The next picture shows titled borders. Using a titled border, you can convert any border into one that displays a text description. 下图显示了带标题的边框。使用带标题的边框,可以将任何边框转换为显示文本描述的边框。If you don't specify a border, a look-and-feel-specific border is used. 如果不指定边框,则使用外观特定的边框。For example, the default titled border in the Java look and feel uses a gray line, and the default titled border in the Windows look and feel uses an etched border. 例如,Java外观中的默认标题边框使用灰色线,而Windows外观中的缺省标题边框使用蚀刻边框。By default, the title straddles the upper left of the border, as shown at the top of the following figure.默认情况下,标题横跨边框的左上角,如下图顶部所示。

BorderDemo: Titled Borders

The next picture shows compound borders. 下图显示复合边框。With compound borders, you can combine any two borders, which can themselves be compound borders.使用复合边界,可以组合任意两个边界,这两个边界本身可以是复合边界。

BorderDemo: Compound Borders

Using the Borders Provided by Swing使用Swing提供的边框

The code that follows shows how to create and set the borders you saw in the preceding figures. 下面的代码显示了如何创建和设置您在前面的图中看到的边界。You can find the program's code in BorderDemo.java.您可以在BorderDemo.java中找到该程序的代码。

//Keep references to the next few borders,
//for use in titles and compound borders.
Border blackline, raisedetched, loweredetched,
       raisedbevel, loweredbevel, empty;

blackline = BorderFactory.createLineBorder(Color.black);
raisedetched = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
loweredetched = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
raisedbevel = BorderFactory.createRaisedBevelBorder();
loweredbevel = BorderFactory.createLoweredBevelBorder();
empty = BorderFactory.createEmptyBorder();

//Simple borders
jComp1.setBorder(blackline);
jComp2.setBorder(raisedbevel);
jComp3.setBorder(loweredbevel);
jComp4.setBorder(empty);

//Matte borders
ImageIcon icon = createImageIcon("images/wavy.gif",
                                 "wavy-line border icon"); //20x22

jComp5.setBorder(BorderFactory.createMatteBorder(
                                   -1, -1, -1, -1, icon));
jComp6.setBorder(BorderFactory.createMatteBorder(
                                    1, 5, 1, 1, Color.red));
jComp7.setBorder(BorderFactory.createMatteBorder(
                                    0, 20, 0, 0, icon));

//Titled borders
TitledBorder title;
title = BorderFactory.createTitledBorder("title");
jComp8.setBorder(title);

title = BorderFactory.createTitledBorder(
                       blackline, "title");
title.setTitleJustification(TitledBorder.CENTER);
jComp9.setBorder(title);

title = BorderFactory.createTitledBorder(
                       loweredetched, "title");
title.setTitleJustification(TitledBorder.RIGHT);
jComp10.setBorder(title);

title = BorderFactory.createTitledBorder(
                       loweredbevel, "title");
title.setTitlePosition(TitledBorder.ABOVE_TOP);
jComp11.setBorder(title);

title = BorderFactory.createTitledBorder(
                       empty, "title");
title.setTitlePosition(TitledBorder.BOTTOM);
jComp12.setBorder(title);

//Compound borders
Border compound;
Border redline = BorderFactory.createLineBorder(Color.red);

//This creates a nice frame.
compound = BorderFactory.createCompoundBorder(
                          raisedbevel, loweredbevel);
jComp13.setBorder(compound);

//Add a red outline to the frame.
compound = BorderFactory.createCompoundBorder(
                          redline, compound);
jComp14.setBorder(compound);

//Add a title to the red-outlined frame.
compound = BorderFactory.createTitledBorder(
                          compound, "title",
                          TitledBorder.CENTER,
                          TitledBorder.BELOW_BOTTOM);
jComp15.setBorder(compound);

As you probably noticed, the code uses the BorderFactory class to create each border. 正如您可能注意到的,代码使用BorderFactory类创建每个边框。The BorderFactory class, which is in the javax.swing package, returns objects that implement the Border interface.javax.swing包中的BorderFactory类返回实现Border接口的对象。

The Border interface, as well as its Swing-provided implementations, is in the javax.swing.border package. Border接口及其Swing提供的实现位于javax.swing.border包中。You often don't need to directly use anything in the border package, except when specifying constants that are specific to a particular border class or when referring to the Border type.您通常不需要直接使用border包中的任何内容,除非指定特定于特定border类的常量或引用Border类型。

Creating Custom Borders创建自定义边框

If BorderFactory doesn't offer you enough control over a border's form, then you might need to directly use the API in the border package — or even define your own border. 如果BorderFactory无法为您提供对边框表单的足够控制,那么您可能需要直接使用边框包中的API—甚至定义自己的边界。In addition to containing the Border interface, the border package contains the classes that implement the borders you've already seen: LineBorder, EtchedBorder, BevelBorder, EmptyBorder, MatteBorder, TitledBorder, and CompoundBorder. 除了包含Border接口外,Border包还包含实现您已经看到的边界的类:LineBorderEtchedBorderBevelBorderEmptyBorderMatteBorderTitledBorderCompoundBorderThe border package also contains a class named SoftBevelBorder, which produces a result similar to BevelBorder, but with softer edges.border包还包含一个名为SoftBevelBorder的类,该类生成的结果类似于BevelBoorder,但边缘较软。

If none of the Swing borders is suitable, you can implement your own border. 如果没有合适的Swing边界,您可以实现自己的边界。Generally, you do this by creating a subclass of the AbstractBorder class. 通常,您可以通过创建AbstractBorder类的子类来实现这一点。In your subclass, you must implement at least one constructor and the following two methods:在子类中,必须实现至少一个构造函数和以下两个方法:

If a custom border has insets (and they typically have insets) you need to override both AbstractBorder.getBorderInsets(Component c) and AbstractBorder.getBorderInsets(Component c, Insets insets) to provide the correct insets.如果自定义边框具有插入(并且它们通常具有插入),则需要重写AbstractBorder.getBorderInsets(Component c)AbstractBorder.getBorderInsets(Component c, Insets insets)以提供正确的插入。

For examples of implementing borders, see the source code for the classes in the javax.swing.border package.有关实现边界的示例,请参阅javax.swing.border包中类的源代码。

The Border API

The following tables list the commonly used border methods. 下表列出了常用的边界方法。The API for using borders falls into two categories:使用边界的API分为两类:

Creating a Border with BorderFactory使用BorderFactory创建边框
Method方法 Purpose目的
Border createLineBorder(Color)
Border createLineBorder(Color, int)
Create a line border. 创建线条边框。The first argument is a java.awt.Color object that specifies the color of the line. 第一个参数是指定线条颜色的java.awt.Color对象。The optional second argument specifies the width in pixels of the line.可选的第二个参数指定线条的宽度(以像素为单位)。
Border createEtchedBorder()
Border createEtchedBorder(Color, Color)
Border createEtchedBorder(int)
Border createEtchedBorder(int, Color, Color)
Create an etched border. 创建蚀刻的边框。The optional Color arguments specify the highlight and shadow colors to be used. 可选的Color参数指定要使用的高光和阴影颜色。The methods with int arguments allow the border methods to be specified as either EtchedBorder.RAISED or EtchedBorder.LOWERED. 带有int参数的方法允许将border方法指定为EtchedBorder.RAISEDEtchedBorder.LOWEREDThe methods without the int arguments create a lowered etched border.不带int参数的方法会创建一个较低的蚀刻边界。
Border createLoweredBevelBorder() Create a border that gives the illusion of the component being lower than the surrounding area.创建一个边界,使组件看起来低于周围区域。
Border createRaisedBevelBorder() Create a border that gives the illusion of the component being higher than the surrounding area.创建一个边界,使组件看起来比周围区域高。

Border createBevelBorder(int, Color, Color)
Border createBevelBorder(int, Color, Color, Color, Color)
Create a raised or lowered beveled border, specifying the colors to use. 创建凸起或降低的倒角边框,指定要使用的颜色。The integer argument can be either BevelBorder.RAISED or BevelBorder.LOWERED. 整数参数可以是BevelBorder.RAISEDBevelBoorder.LOWEREDWith the three-argument constructor, you specify the highlight and shadow colors. 使用三参数构造函数,可以指定高亮和阴影颜色。With the five-argument constructor, you specify the outer highlight, inner highlight, outer shadow, and inner shadow colors, in that order.使用五参数构造函数,可以按顺序指定外部高光、内部高光、外部阴影和内部阴影颜色。
Border createEmptyBorder()
Border createEmptyBorder(int, int, int, int)
Create an invisible border. 创建不可见的边界。If you specify no arguments, then the border takes no space, which is useful when creating a titled border with no visible boundary. 如果未指定参数,则边框不占用空间,这在创建没有可见边界的带标题边框时很有用。The optional arguments specify the number of pixels that the border occupies at the top, left, bottom, and right (in that order) of whatever component uses it. 可选参数指定边框在使用它的任何组件的顶部、左侧、底部和右侧(按此顺序)占据的像素数。This method is useful for putting empty space around your components.此方法对于在组件周围放置空白空间很有用。
MatteBorder createMatteBorder(int, int, int, int, Color)
MatteBorder createMatteBorder(int, int, int, int, Icon)
Create a matte border. 创建无光边框。The integer arguments specify the number of pixels that the border occupies at the top, left, bottom, and right (in that order) of whatever component uses it. 整数参数指定边框在使用它的任何组件的顶部、左侧、底部和右侧(按此顺序)所占的像素数。The color argument specifies the color which with the border should fill its area. color参数指定带边框的颜色应填充其区域。The icon argument specifies the icon which with the border should tile its area.icon参数指定带边框的图标应平铺其区域。
TitledBorder createTitledBorder(String)
TitledBorder createTitledBorder(Border)
TitledBorder createTitledBorder(Border, String)
TitledBorder createTitledBorder(Border, String, int, int)
TitledBorder createTitledBorder(Border, String, int, int, Font)
TitledBorder createTitledBorder(Border, String, int, int, Font, Color)
Create a titled border. 创建带标题的边框。The string argument specifies the title to be displayed. 字符串参数指定要显示的标题。The optional font and color arguments specify the font and color to be used for the title's text. 可选的字体和颜色参数指定要用于标题文本的字体和色彩。The border argument specifies the border that should be displayed along with the title. border参数指定应与标题一起显示的边框。If no border is specified, then a look-and-feel-specific default border is used. 如果未指定边框,则使用外观特定的默认边框。

By default, the title straddles the top of its companion border and is left-justified. 默认情况下,标题跨越其对应边框的顶部,并左对齐。The optional integer arguments specify the title's position and justification, in that order. 可选的整数参数按顺序指定标题的位置和对齐方式。TitledBorder defines these possible positions: ABOVE_TOP, TOP (the default), BELOW_TOP, ABOVE_BOTTOM, BOTTOM, and BELOW_BOTTOM. 定义这些可能的位置:ABOVE_TOPTOP(默认值)、BELOW_TOPABOVE_BOTTOMBOTTOMBELOW_BOTTOMYou can specify the justification as LEADING (the default), CENTER, or TRAILING. 可以将对正指定为LEADING(默认值)、CENTERTRAILINGIn locales with Western alphabets LEADING is equivalent to LEFT and TRAILING is equivalent to RIGHT.在使用西方字母的区域设置中,LEADING等同于LEFTTRAILING相当于RIGHT


CompoundBorder createCompoundBorder(Border, Border)
Combine two borders into one. 将两个边界合并为一个。The first argument specifies the outer border; the second, the inner border.第一个参数指定外边界;第二,内部边界。
Setting or Getting a Component's Border设置或获取组件的边框
Method方法 Purpose目的
void setBorder(Border)
Border getBorder()
Set or get the border of the receiving JComponent.设置或获取接收JComponent的边界。
void setBorderPainted(boolean)
boolean isBorderPainted()
(in AbstractButton, JMenuBar, JPopupMenu, JProgressBar, and JToolBar)
Set or get whether the border of the component should be displayed.设置或获取是否应显示组件的边框。

Examples that Use Borders使用边框的示例

Many examples in this lesson use borders. 本课中的许多示例使用边界。The following table lists a few interesting cases.下表列出了一些有趣的案例。

Example示例 Where Described描述位置 Notes备注
BorderDemo This section本节 Shows an example of each type of border that BorderFactory can create. 显示BorderFactory可以创建的每种类型的边框的示例。Also uses an empty border to add breathing space between each pane and its contents.还使用空边框在每个窗格及其内容之间添加呼吸空间。
BoxAlignmentDemo How to Use BoxLayout如何使用BoxLayout Uses titled borders.使用带标题的边框。
BoxLayoutDemo How to Use BoxLayout如何使用BoxLayout Uses a red line to show where the edge of a container is, so that you can see how the extra space in a box layout is distributed.使用红线显示容器边缘的位置,以便您可以看到方框布局中的额外空间是如何分布的。
ComboBoxDemo2 How to Use Combo Boxes如何使用组合框 Uses a compound border to combine a line border with an empty border. 使用复合边框将线条边框与空边框合并。The empty border provides space between the line and the component's innards.空边界在线和组件内部之间提供了空间。

Previous page: How to Use Icons
Next page: Solving Common Component Problems