如何将关闭按钮添加到JTabbedPane选项卡?

2022-09-01 09:32:05

我正在使用JTabbedPane,我需要在选项卡中添加一个关闭按钮来关闭当前按钮。

我一直在搜索,据我所知,我必须从JPanel扩展并添加关闭按钮,就像他们在这里所说的那样但是,有没有办法添加扩展JTabbedPane的关闭按钮,或者有更简单的方法可以做到这一点?

提前感谢,我真的很感激你的时间和你的帮助。


答案 1

从本质上讲,您将需要为选项卡提供“渲染器”。请查看 JTabbedPane.setTabComponentAt(...) 了解更多信息。

基本思想是提供将在选项卡上布局的组件。

我通常会创建一个JPanel,并在其上添加一个JLabel(用于标题),并根据我想要显示的内容,添加某种充当关闭操作的控件。

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


答案 2

我找到了一个选项卡示例(来自java站点),至少在他们的站点中是这样。(虽然我认为,当我过去尝试它时,它也关闭了当前选定的选项卡,尽管当您运行它们的示例时它可以正常工作,尽管我认为当我将其更新为在选项卡式java记事本上工作时,它正在关闭当前选定的选项卡,尽管也许我做错了。

http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TabComponentsDemoProject/src/components/ButtonTabComponent.java

是的,我的东西现在正在工作!这将适用于实际选项卡,而不是当前选定的选项卡!


推荐