基本上,您将需要为该选项卡提供“渲染器”。看看
JTabbedPane.setTabComponentAt(…)了解更多信息。
基本思想是提供一个将在标签上布局的组件。
我通常创建一个JPanel,我添加了一个JLabel(用于标题),根据我想要显示的内容,可以使用一些作为close操作的控件。
tabPane.addTab(title, tabBody);
int index = tabPane.indexOfTab(title);
JPanel pnlTab = new JPanel(new GridBagLayout());
pnlTab.setOpaque(false);
JLabel lblTitle = new JLabel(title);
JButton btnClose = new JButton("x");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
pnlTab.add(lblTitle, gbc);
gbc.gridx++;
gbc.weightx = 0;
pnlTab.add(btnClose, gbc);
tabPane.setTabComponentAt(index, pnlTab);
btnClose.addActionListener(myCloseActionHandler);
现在在别的地方,我建立了动作处理程序…
public class MyCloseActionHandler implements ActionListener {
public void actionPerformed(ActionEvent evt) {
Component selected = tabPane.getSelectedComponent();
if (selected != null) {
tabPane.remove(selected);
// It would probably be worthwhile getting the source
// casting it back to a JButton and removing
// the action handler reference ;)
}
}
}
现在,您可以轻松地使用任何您喜欢的组件,并附加鼠标监听器并监视鼠标点击次数…
更新
以上示例将仅删除当前活动的选项卡,有几种方法来解决此问题。
最好的可能是提供一些方法来找到与它相关联的选项卡的动作
public class MyCloseActionHandler implements ActionListener {
private String tabName;
public MyCloseActionHandler(String tabName) {
this.tabName = tabName;
}
public String getTabName() {
return tabName;
}
public void actionPerformed(ActionEvent evt) {
int index = tabPane.indexOfTab(getTabName());
if (index >= 0) {
tabPane.removeTabAt(index);
// It would probably be worthwhile getting the source
// casting it back to a JButton and removing
// the action handler reference ;)
}
}
}
这使用标签的名称(与JTabbedPane#addTab一起使用)来查找,然后删除选项卡及其关联的组件…