Java tab bar: display icon next to title

can I display an “X” in the tab header used to close the tab? Thanks

+5
source share
2 answers

I would suggest looking at the tutorial How to Use Dashboards and Scrolling Down to the Tabs with Custom Components.

Also, if you look at the example index link inside this section, the code example is provided.

+6
source

I actually just created an implementation of this myself. :)

Something like that:

/* 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 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);
    }
 });
+3
source

All Articles