如何向JTabbedPane标签添加关闭按钮?

Her*_*man 27 java swing tabs jtabbedpane

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

我一直在搜索,据我所知,我必须从JPanel扩展并添加关闭按钮,因为他们在这里说 但是,有没有办法添加延伸JTabbedPane的关闭按钮或有更简单的方法吗?

在此先感谢,我非常感谢您的时间和帮助.

Mad*_*mer 43

基本上,您将需要为选项卡提供"渲染器".查看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);
Run Code Online (Sandbox Code Playgroud)

现在在其他地方,我建立了动作处理程序......

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 ;)

        }

    }

}
Run Code Online (Sandbox Code Playgroud)

现在,您可以轻松使用您喜欢的任何组件并将鼠标监听器连接到它并监控鼠标点击...

更新

以上示例仅删除当前活动的选项卡,有几种方法可以解决此问题.

最好的方法是为行动找到与之相关的标签提供一些手段......

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 ;)

        }

    }

}   
Run Code Online (Sandbox Code Playgroud)

这使用tab的名称(与之一起使用JTabbedPane#addTab)来查找然后删除选项卡及其关联的组件...


Mon*_*ver 6

我发现了一个标签示例(来自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

是的,我现在正在努力!这将适用于实际的选项卡,而不是当前选定的选项卡!