Documentation

The Java™ Tutorials
Hide TOC
How to Use Tabbed Panes如何使用选项卡式窗格
Trail: Creating a GUI With Swing
Lesson: Using Swing Components
Section: How to Use Various Components

How to Use Tabbed Panes如何使用选项卡式窗格

With the JTabbedPane class, you can have several components, such as panels, share the same space. 使用JTabbedPane类,可以让多个组件(如面板)共享相同的空间。The user chooses which component to view by selecting the tab corresponding to the desired component. 用户通过选择与所需组件相对应的选项卡来选择要查看的组件。If you want similar functionality without the tab interface, you can use a card layout instead of a tabbed pane.如果您想要类似的功能而不需要选项卡界面,可以使用卡片布局而不是选项卡式窗格。

To Create Tabbed Panes创建选项卡式窗格的步骤

To create a tabbed pane, instantiate JTabbedPane, create the components you wish it to display, and then add the components to the tabbed pane using the addTab method.要创建选项卡式窗格,请实例化JTabbedPane,创建希望它显示的组件,然后使用addTab方法将组件添加到选项卡式窗格。

The following picture introduces an application called TabbedPaneDemo that has a tabbed pane with four tabs.下图介绍了一个名为TabbedPaneDemo的应用程序,它有一个带有四个选项卡的选项卡式窗格。

A screenshot of TabbedPaneDemo

Try this: 
  1. Click the Launch button to run TabbedPaneDemo using Java™ Web Start (download JDK 7 or later). 单击启动按钮,使用Java™Web启动运行TabbedPaneDemo(下载JDK 7或更高版本)。Alternatively, to compile and run the example yourself, consult the example index.或者,要自己编译和运行示例,请参考示例索引Launches the TabbedPaneDemo Application
  2. Put the cursor over a tab.将光标放在选项卡上。
    The tool tip associated with the tab appears. 将显示与选项卡关联的工具提示。As a convenience, you can specify tool tip text when you add a component to the tabbed pane.为方便起见,可以在将组件添加到选项卡式窗格时指定工具提示文本。
  3. Select a tab by clicking it.通过单击选项卡来选择选项卡。
    The tabbed pane displays the component corresponding to the tab.选项卡式窗格显示与选项卡对应的组件。
  4. Select a tab by entering its mnemonic.通过输入选项卡的助记符来选择选项卡。
    For example, in the Java look and feel you can select the tab labeled "Tab 3" by typing Alt-3.例如,在Java外观中,您可以通过键入Alt-3来选择标记为“Tab3”的选项卡。
  5. Navigate between scrollable tabs.在可滚动选项卡之间导航。
    This example provides scrollable tabs. 此示例提供了可滚动的选项卡。Resize the dialog box by moving its left or right boundary so that tabs do not fit within the dialog. 通过移动对话框的左边界或右边界调整对话框的大小,使选项卡不适合对话框。Scroll arrows appear next to the tabs.滚动箭头出现在选项卡旁边。
    Click the arrow to view one of the hidden tabs.单击箭头可查看其中一个隐藏选项卡。
    Note that clicking the arrow only reveals hidden tabs. 请注意,单击箭头仅显示隐藏的选项卡。It does not select a new tab.它不选择新选项卡。

As the TabbedPaneDemo example shows, a tab can have a tool tip and a mnemonic, and it can display both text and an image.TabbedPaneDemo示例所示,选项卡可以具有工具提示和助记符,并且可以显示文本和图像。

Tab Placement标签放置

The default tab placement is set to the TOP location, as shown above. 默认选项卡放置设置为TOP位置,如上所示。You can change the tab placement to LEFT, RIGHT, TOP or BOTTOM by using the setTabPlacement method.可以使用setTabPlacement方法将选项卡放置更改为LEFTRIGHTTOPBOTTOM

Code for Tabbed Panes选项卡式窗格的代码

The following code from TabbedPaneDemo.java creates the tabbed pane in the previous example. TabbedPaneDemo.java中的以下代码在前面的示例中创建了选项卡式窗格。Note that no event-handling code is necessary. 请注意,不需要事件处理代码。The JTabbedPane object takes care of mouse and keyboard events for you.JTabbedPane对象为您处理鼠标和键盘事件。

JTabbedPane tabbedPane = new JTabbedPane();
ImageIcon icon = createImageIcon("images/middle.gif");

JComponent panel1 = makeTextPanel("Panel #1");
tabbedPane.addTab("Tab 1", icon, panel1,
                  "Does nothing");
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);

JComponent panel2 = makeTextPanel("Panel #2");
tabbedPane.addTab("Tab 2", icon, panel2,
                  "Does twice as much nothing");
tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);

JComponent panel3 = makeTextPanel("Panel #3");
tabbedPane.addTab("Tab 3", icon, panel3,
                  "Still does nothing");
tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);

JComponent panel4 = makeTextPanel(
        "Panel #4 (has a preferred size of 410 x 50).");
panel4.setPreferredSize(new Dimension(410, 50));
tabbedPane.addTab("Tab 4", icon, panel4,
                      "Does nothing at all");
tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);

As the previous code shows, the addTab method handles the bulk of the work in setting up a tab in a tabbed pane. 正如前面的代码所示,addTab方法处理了在选项卡式窗格中设置选项卡的大部分工作。The addTab method has several forms, but they all use both a string title and the component to be displayed by the tab. addTab方法有几种形式,但它们都使用字符串标题和选项卡显示的组件。Optionally, you can specify an icon and tool tip string. 或者,可以指定图标和工具提示字符串。The text or icon (or both) can be null. 文本或图标(或两者)可以为空。Another way to create a tab is to use the insertTab method, which lets you specify the index of the tab you're adding. 创建选项卡的另一种方法是使用insertTab方法,该方法允许您指定要添加的选项卡的索引。Note that the addTab method does not allow index specification in this step.注意,addTab方法不允许在此步骤中指定索引。

To Switch to Specific Tabs切换到特定选项卡

There are three ways to switch to specific tabs using GUI.使用GUI切换到特定选项卡有三种方法。

  1. Using a mouse.使用鼠标。 To switch to a specific tab, the user clicks it with the mouse.要切换到特定选项卡,用户用鼠标单击它。
  2. Using keyboard arrows.使用键盘箭头。 When the JTabbedPane object has the focus, the keyboard arrows can be used to switch from tab to tab.JTabbedPane对象具有焦点时,可以使用键盘箭头在选项卡之间切换。
  3. Using key mnemonics.使用键助记符。 The setMnemonicAt method allows the user to switch to a specific tab using the keyboard. setMnemonicAt方法允许用户使用键盘切换到特定选项卡。For example, setMnemonicAt(3, KeyEvent.VK_4) makes '4' the mnemonic for the fourth tab (which is at index 3, since the indices start with 0); pressing Alt-4 makes the fourth tab's component appear. 例如,setMnemonicAt(3, KeyEvent.VK_4)使“4”成为第四个选项卡的助记符(即索引3处,因为索引从0开始);按Alt-4将显示第四个选项卡的组件。Often, a mnemonic uses a character in the tab's title that is then automatically underlined.通常,助记符在标签标题中使用一个字符,然后自动加下划线。

To switch to a specific tab programmatically, use the setSelectedIndex or the setSelectedComponent methods.要以编程方式切换到特定选项卡,请使用setSelectedIndex方法或setSelectedComponent组件方法。

Preferred Size in Tabs标签中的首选大小

When building components to add to a tabbed pane, keep in mind that no matter which child of a tabbed pane is visible, each child gets the same amount of space in which to display itself. 在构建要添加到选项卡式窗格的组件时,请记住,无论选项卡式窗格中的哪个子项可见,每个子项都会获得相同的空间量来显示自己。The preferred size of the tabbed pane is just big enough to display its tallest child at its preferred height, and its widest child at its preferred width. 选项卡式窗格的首选大小刚好足以在其首选高度显示其最高子级,并在其首选宽度显示其最宽子级。Similarly, the minimum size of the tabbed pane depends on the biggest minimum width and height of all its children.类似地,选项卡式窗格的最小大小取决于其所有子项的最大最小宽度和高度。

In the TabbedPaneDemo example, the fourth panel has a preferred width and height that are larger than those of the other panels. TabbedPaneDemo示例中,第四个面板的首选宽度和高度大于其他面板的宽度和高度。Thus, the preferred size of the tabbed pane is just big enough to display the fourth panel at its preferred size. 因此,选项卡式窗格的首选大小刚好足以以其首选大小显示第四个面板。Every panel gets exactly the same amount of space — 410 pixels wide and 50 high, assuming the tabbed pane is at its preferred size. 每个面板获得完全相同的空间量;410像素宽和50像素高,假设选项卡式窗格处于其优选大小。If you do not understand how preferred size is used, please refer to How Layout Management Works.如果您不了解如何使用首选尺寸,请参阅布局管理的工作原理

Tabs With Custom Components带有自定义组件的选项卡

The TabComponentsDemo example introduces a tabbed pane whose tabs contain real components. TabComponentsDemo示例引入了一个选项卡式窗格,其选项卡包含实际组件。The use of custom components brings new features such as buttons, combo boxes, labels and other components to tabs, and allows more complex user interaction.自定义组件的使用为选项卡带来了新功能,如按钮、组合框、标签和其他组件,并允许更复杂的用户交互。

Here is a tabbed pane with close buttons on its tabs.这是一个选项卡式窗格,其选项卡上有关闭按钮。

A screenshot of TabComponentsDemo

Try this: 
  1. Click the Launch button to run TabComponentsDemo using Java™ Web Start (download JDK 7 or later). 单击启动按钮,使用Java™Web启动运行TabComponentsDemo(下载JDK 7或更高版本)。Alternatively, to compile and run the example yourself, consult the example index.或者,要自己编译和运行示例,请参考示例索引Launches the TabComponentsDemo Application
  2. Put the cursor over a tab.将光标放在选项卡上。
  3. Select a tab by clicking it (make sure not to hit the little cross).通过单击选项卡来选择选项卡(确保不要碰到小十字)。
  4. Put the cursor over one of the widgets with a little cross.将光标放在其中一个带有小十字的小部件上。
    The cross turns magenta and gets enclosed in a square. 十字架变成了洋红,并被包围在一个正方形中。A tool tip associated with the close button appears.将出现与关闭按钮关联的工具提示。
    Click the cross with the left mouse button to close the tab.用鼠标左键单击十字以关闭选项卡。
  5. Restore the tabs that have been removed by choosing the Reset JTabbedPane item from the Options menu.通过从“选项”菜单中选择“重置JTabbedPane”项,恢复已删除的选项卡。
  6. Note that tabs with custom components are displayed on top of original tabbed pane tabs.请注意,带有自定义组件的选项卡显示在原始选项卡窗格选项卡的顶部。
    To view the tabs underneath, open the Options menu and clear the Use TabComponents check box.要查看下面的选项卡,请打开“选项”菜单并清除“使用选项卡组件”复选框。
  7. Display the tabs with components by selecting the Use TabComponents check box again.再次选中“使用选项卡组件”复选框,显示带有组件的选项卡。
  8. Close all tabs. Now the tabbed pane is empty.关闭所有选项卡。现在选项卡窗格为空。

To Remove Tabs要删除选项卡:

The following code from ButtonTabComponent.java removes a tab from the tabbed pane. ButtonTabComponent.java中的以下代码从选项卡窗格中删除了一个选项卡。Note that event-handling code is necessary. 请注意,事件处理代码是必需的。Since each tab contains a real JButton object, you must attach an ActionListener to the close button. 由于每个选项卡都包含一个真实的JButton对象,因此必须将ActionListener附加到关闭按钮。As the user clicks the button, the actionPerformed method determines the index of the tab it belongs to and removes the corresponding tab.当用户单击按钮时,actionPerformed方法确定其所属选项卡的索引,并删除相应的选项卡。

public void actionPerformed(ActionEvent e) {
int i = pane.indexOfTabComponent(ButtonTabComponent.this);
    if (i != -1) {
    pane.remove(i);
    }
}

To Give Titles to Customized Tabs为自定义选项卡提供标题

The code below, taken from ButtonTabComponent.java, shows how a customized tab component gets a title from an original tabbed pane tab.下面的代码取自ButtonTabComponent.java,显示了自定义选项卡组件如何从原始选项卡窗格选项卡获取标题。

JLabel label = new JLabel(title) {
    public String getText() {
        int i = pane.indexOfTabComponent(ButtonTabComponent.this);
        if (i != -1) {
            return pane.getTitleAt(i);
        }
        return null;
    }
};

The Tabbed Pane API选项卡式窗格API

The following tables list the commonly used JTabbedPane constructors and methods. 下表列出了常用的JTabbedPane构造函数和方法。The API for using tabbed panes falls into the following categories:使用选项卡式窗格的API分为以下几类:

Creating and Setting Up a Tabbed Pane创建和设置选项卡式窗格
Method or Constructor方法或构造函数 Purpose目的
JTabbedPane()
JTabbedPane(int)
JTabbedPane(int, int)
Creates a tabbed pane. The first optional argument specifies where the tabs should appear. 创建选项卡式窗格。第一个可选参数指定选项卡的显示位置。By default, the tabs appear at the top of the tabbed pane. 默认情况下,选项卡显示在选项卡窗格的顶部。You can specify these positions (defined in the SwingConstants interface, which JTabbedPane implements): TOP, BOTTOM, LEFT, RIGHT. 您可以指定这些位置(在SwingConstants接口中定义,JTabbedPane实现了该接口):TOPBOTTOMLEFTRIGHTThe second optional argument specifies the tab layout policy. 第二个可选参数指定选项卡布局策略。You can specify one of these policies (defined in JTabbedPane): WRAP_TAB_LAYOUT or SCROLL_TAB_LAYOUT.您可以指定其中一个策略(在JTabbedPane中定义):WRAP_TAB_LAYOUTSCROLL_TAB_LAYOUT
addTab(String, Icon, Component, String)
addTab(String, Icon, Component)
addTab(String, Component)
Adds a new tab to the tabbed pane. The first argument specifies the text on the tab. 将新选项卡添加到选项卡式窗格。第一个参数指定选项卡上的文本。The optional icon argument specifies the tab's icon. 可选图标参数指定选项卡的图标。The component argument specifies the component that the tabbed pane should show when the tab is selected. component参数指定选择选项卡时选项卡窗格应显示的组件。The fourth argument, if present, specifies the tool tip text for the tab.第四个参数(如果存在)指定选项卡的工具提示文本。
void setTabLayoutPolicy(int)
int getTabLayoutPolicy()
Sets or gets the policy that the tabbed pane uses in laying out tabs when all tabs do not fit within a single run. 设置或获取选项卡窗格在所有选项卡不适合单个运行时用于布局选项卡的策略。Possible values are WRAP_TAB_LAYOUT and SCROLL_TAB_LAYOUT. 可能的值是WRAP_TAB_LAYOUTSCROLL_TAD_LAYThe default policy is WRAP_TAB_LAYOUT.默认策略是WRAP_TAB_LAYOUT
void setTabPlacement(int)
int getTabPlacement()
Sets or gets the location where the tabs appear relative to the content. 设置或获取选项卡相对于内容显示的位置。Possible values (defined in SwingConstants, which is implemented by JTabbedPane) are TOP, BOTTOM, LEFT, and RIGHT.可能的值(在SwingConstants中定义,由JTabbedPane实现)为TOPBOTTOMLEFTRIGHT
Inserting, Removing, Finding, and Selecting Tabs插入、删除、查找和选择选项卡
Method方法 Purpose目的
insertTab(String, Icon, Component, String, int) Inserts a tab at the specified index, where the first tab is at index 0. 在指定索引处插入选项卡,其中第一个选项卡位于索引0处。The arguments are the same as for addTab.参数与addTab的参数相同。
remove(Component)
removeTabAt(int)
Removes the tab corresponding to the specified component or index.删除与指定组件或索引对应的选项卡。
removeAll() Removes all tabs.删除所有选项卡。
int indexOfComponent(Component)
int indexOfTab(String)
int indexOfTab(Icon)
Returns the index of the tab that has the specified component, title, or icon.返回具有指定组件、标题或图标的选项卡的索引。
void setSelectedIndex(int)
void setSelectedComponent(Component)
Selects the tab that has the specified component or index. 选择具有指定组件或索引的选项卡。Selecting a tab has the effect of displaying its associated component.选择选项卡具有显示其关联组件的效果。
int getSelectedIndex()
Component getSelectedComponent()
Returns the index or component for the selected tab.返回所选选项卡的索引或组件。
Changing Tab Appearance更改选项卡外观
Method方法 Purpose目的
void setComponentAt(int, Component)
Component getComponentAt(int)
Sets or gets which component is associated with the tab at the specified index. 设置或获取与指定索引处的选项卡关联的组件。The first tab is at index 0.第一个选项卡位于索引0处。
void setTitleAt(int, String)
String getTitleAt(int)
Sets or gets the title of the tab at the specified index.设置或获取指定索引处选项卡的标题。
void setIconAt(int, Icon)
Icon getIconAt(int)
void setDisabledIconAt(int, Icon)
Icon getDisabledIconAt(int)
Sets or gets the icon displayed by the tab at the specified index.设置或获取选项卡在指定索引处显示的图标。
void setBackgroundAt(int, Color)
Color getBackgroundAt(int)
void setForegroundAt(int, Color)
Color getForegroundAt(int)
Sets or gets the background or foreground color used by the tab at the specified index. 设置或获取选项卡在指定索引处使用的背景色或前景色。By default, a tab uses the tabbed pane's background and foreground colors. 默认情况下,选项卡使用选项卡窗格的背景色和前景色。For example, if the tabbed pane's foreground is black, then each tab's title is black except for any tabs for which you specify another color using setForegroundAt.例如,如果选项卡式窗格的前景为黑色,则每个选项卡的标题均为黑色,但使用setForegroundAt为其指定其他颜色的选项卡除外。
void setEnabledAt(int, boolean)
boolean isEnabledAt(int)
Sets or gets the enabled state of the tab at the specified index.设置或获取指定索引处选项卡的启用状态。
void setMnemonicAt(int, int)
int getMnemonicAt(int)
Sets or gets the keyboard mnemonic for accessing the specified tab.设置或获取用于访问指定选项卡的键盘助记符。
void setDisplayedMnemonicIndexAt(int, int)
int getDisplayedMnemonicIndexAt(int)
Sets or gets which character should be decorated to represent the mnemonic. 设置或获取应修饰哪个字符以表示助记符。This is useful when the mnemonic character appears multiple times in the tab's title and you don't want the first occurrence underlined.当助记符在选项卡标题中多次出现并且您不希望第一次出现时加下划线时,这很有用。
void setToolTipTextAt(int, String)
String getToolTipTextAt(int)
Sets or gets the text displayed on tool tips for the specified tab.设置或获取指定选项卡的工具提示上显示的文本。
Setting Up Custom Components on Tabs在选项卡上设置自定义组件
Method方法 Purpose目的
void setTabComponentAt(int, Component) Sets the component that is responsible for rendering the title or icon (or both) for the tab specified by the first argument. 设置负责呈现由第一个参数指定的选项卡的标题或图标(或两者)的组件。When a null value is specified, JTabbedPane renders the title or icon. The same component cannot be used for several tabs.当指定空值时,JTabbedPane呈现标题或图标。同一组件不能用于多个选项卡。
Component getTabComponentAt(int) Gets the tab component for the tab at the index specified by the argument. 获取参数指定索引处选项卡的选项卡组件。If there is no tab component for the specified tab, a null value is returned.如果指定选项卡没有选项卡组件,则返回空值。
int indexOfTabComponent(Component) Checks if the specified component belongs to one of the tabs. Return the index of the corresponding tab or -1 if there is no such a tab.检查指定的组件是否属于其中一个选项卡。返回相应选项卡的索引,如果没有这样的选项卡,则返回-1。

Examples That Use Tabbed Panes使用选项卡式窗格的示例

This table lists examples that use JTabbedPane and points to where those examples are described.下表列出了使用JTabbedPane的示例,并指出了这些示例的描述位置。

Example示例 Where Described描述位置 Notes备注
TabbedPaneDemo This page本页 Demonstrates a few tabbed pane features, such as tool tips, icons, scrollable layout, and mnemonics.演示一些选项卡式窗格功能,如工具提示、图标、可滚动布局和助记符。
TabComponentsDemo This page本页 Demonstrates custom components on tabs. Uses a tabbed pane with close buttons.演示选项卡上的自定义组件。使用带有关闭按钮的选项卡式窗格。
BoxAlignmentDemo How to Use BoxLayout如何使用BoxLayout Uses a JTabbedPane as the only child of a frame's content pane.使用JTabbedPane作为框架内容窗格的唯一子级。
BorderDemo How to Use Borders如何使用边框 Uses its tabbed pane in a manner similar to BoxAlignmentDemo.以类似于BoxAlignmentDemo的方式使用其选项卡式窗格。
DialogDemo How to Use Dialogs如何使用对话框 Has a tabbed pane in the center of a frame's content pane, with a label below it.在框架内容窗格的中心有一个选项卡式窗格,其下方有一个标签。

Previous page: How to Use Split Panes
Next page: How to Use Tables