int javax.swing.JTabbedPane.indexOfComponent(Component component)
Returns the index of the tab for the specified component.Returns -1 if there is no tab for this component.
返回选项面板指定组件的索引号,如果选项面板内没有组件,则返回-1
Parameters:component the component for the tabReturns:the first tab which matches this component, or -1if there is no tab for this component
参数:组件,第一个选项面板匹配内匹配这个组件,如果选项面板内没有组件,则返回-1
// jdk1.6之后的新特性,也是实现这个功能的核心所在,在相应下表的tab出放置任何组件
tab.setTabComponentAt(tab.indexOfComponent(jPanel), pane);
在这里,我要向大家介绍JTabbedPane类的三个方法:
void setTabComponentAt(int index,Compomnent component)
——该方法用于给指定index的选项卡标题添加控件,空间可以是任何类型,只要是Component的子类。如果index超出范围,则抛出IndexOutOfBoundsException异常。若选项卡标题上已经有Component组件,则抛出IllegalArgumentException异常。
Component getTabComponent(int index)
——该方法用于获取指定index的选项卡标题上的控件。如果index超出范围,则抛出IndexOutOfBoundsException异常。
int indexOfTabComponent(Component component)
——该方法用于获取标题空间为component的选项卡序号。若没有符合要求的选项卡,则返回-1。
使用这三个方法,就可以设置选项卡标题上的组建了。如果设置为JPanel类型,还可以添加多个组件,这也就不用再为无法添加关闭按钮而郁闷了。
以下代码实现在选项上卡添加删除按钮
设计思路
建立 TabPaneFrame窗体并添加容器,添加JTabbedPane(tab)面板,
在JTabbedPane(tab)面板添加tab选项卡,选项卡是JPanel类型,里面可以添加很多组件。pane是一个JPanel类型,在pane内添加一个标签和一个带“X”的按钮,使用tab.setTabComponentAt(tab.indexOfComponent(jPanel), pane);语句将 pane添加到选项卡的标签位置内,实现关闭选项卡的功能。
package com.zzk.frame;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.WindowConstants;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* Created by SongFei on 2017/11/10.
*/
public class TabPaneFrame extends JFrame {
private static final