I'm working in with a JTabbedPane, I need to add a close button in the tabs to close the current one.
I have been searching and as I understand I must extend from JPanel and add the close button as they say here But, is there a way to add the close buttons extending JTabbedPane or is there a easier way to do it?
Thanks in advance, I really appreciate your time and your help.
Hopefully you have got the answer to your question. I want to give a link that was very useful for me.
JTabbedPane with a close button
Here is some code as well.
I made some changes in the code of oracle.
http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TabComponentsDemoProject/src/components/ButtonTabComponent.java
Giving the possibility to add an icon to the tab , plus the close tab button. Hope that helps.
}
public class ButtonClose extends JPanel {
}
You can have a JLabel named "x" and use the mouseListener
Essentially, you're going to need to supply a "renderer" for the tab. Take a look at JTabbedPane.setTabComponentAt(...) for more information.
The basic idea is to supply a component that will be laid out on the tab.
I typically create a JPanel, onto which I add a JLabel (for the title) and, depending on what I want to display, some kind of control that acts as the close action.
Now somewhere else, I establish the action handler...
Now, you just as easily use any component you like and attach a mouse listener to it and monitor the mouse clicks...
Updated
The above example will only remove the currently active tab, there are a couple of ways to fix this.
The best is to probably provide some means for the action to find the tab it's associated with...
This uses the name of tab (as used with
JTabbedPane#addTab
) to find and then remove the tab and its associated component...I found a tab example (from the java site) that appears to do that, at least in theirs. (Though I thought, when I tried it in the past, that it also closed the currently selected tab, though it works properly when you run their example, though I think when I updated it to work on a tabbed java notepad, it was closing the currently selected tab, though maybe I did it wrong.
http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TabComponentsDemoProject/src/components/ButtonTabComponent.java
Yes, my thing is working now! This WILL work for the actual tab, rather than the currently selected tab!