Java选项卡式窗格:在标题上显示一个图标

时间:2010-11-21 21:35:32

标签: java swing

可以在标签的标题上显示一个“X”图标,用于关闭标签吗? 感谢

2 个答案:

答案 0 :(得分:6)

我建议查看How to Use Tabbed Panes的教程,然后向下滚动到标题为使用自定义组件的标签的部分。

另外,如果您查看该部分中的example index链接,则会给出示例代码。

答案 1 :(得分:3)

我实际上只是自己创建了一个实现。 :)

这样的事情:

/* These need to be final so you can reference them in the MouseAdapter subclass
 * later. I personally just passed them to a method to add the tab, with the
 * parameters marked as final.
 * i.e., public void addCloseableTab(final JTabbedPane tabbedPane, ...)
 */
final Component someComponent = ...; //Whatever component is being added
final JTabbedPane tabbedPane = new JTabbedPane();
//I had my own subclass of AbstractButton, but that's irrelevant in this case
JButton closeButton = new JButton("x");

/*
 * titlePanel is initialized containing a JLabel with the tab title, 
 * and closeButton. (I don't recall the tabbed pane showing a title itself after 
 * setTabComponentAt() is called)
 */
JPanel titlePanel = ...;
tabbedPane.add(someComponent);
tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(someComponent), titlePanel);

closeButton.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
        tabbedPane.remove(someComponent);
    }
 });