Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Tabbed Pane: display an icon close on the title

Tags:

java

swing

it is possible to show an icon "X" on the title of the tab, used to close the tab ? Thanks

like image 620
stighy Avatar asked Nov 21 '10 21:11

stighy


2 Answers

I would suggest looking over the tutorial of, How to Use Tabbed Panes and scroll down to the section entitled Tabs With Custom Components.

Also if you look at the example index link inside that section, the sample code is given.

like image 155
Anthony Forloney Avatar answered Oct 14 '22 20:10

Anthony Forloney


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

Something like this:

/* 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);
    }
 });
like image 30
swilliams Avatar answered Oct 14 '22 19:10

swilliams