java jtabbedpane 关闭_java – 如何添加关闭按钮到JTabbedPane选项卡?

基本上,您将需要为该选项卡提供“渲染器”。看看

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一起使用)来查找,然后删除选项卡及其关联的组件…

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值