In my JTabbedPane
, I am removing tabs in 2 different ways:
tabbedPane.remove(index)
and
tabbedPane.removeAll()
Both work fine in terms of closing the tabs. However, I have a change listener on my TabbedPane
that calls back to another module to report on tab changes. This is where the problem is.
When adding and removing tabs using remove(index)
, the source TabbedPane in the stateChanged()
method contains the correct number of tabs when checking tabbedPane.getTabCount()
.
However, when calling tabbedPane.getTabCount()
after tabbedPane.removeAll()
, the count is still the count that was present immediately before the removeAll()
.
Does anyone have any suggestions?
After looking at the source code, I see what's happening.
JTabbedPane
firesChangeEvents
when the selected tab is changed. But to remove all tabs, it first sets the selected tab to -1 and then removes all the tabs. So when theChangeListener
catches the event, all the tabs are still there.If you want to know the number of tabs at all times, I'm afraid you'll have to iterate through the tabs yourself and remove them one by one.
Here you go; use ContainerListener instead:
Here's a test case that helps to expose the problem.
I think there is a synchronization issue going on; the output is:
It looks as if some change events are being lost.
Update: leaving this in place for posterity, but it's wrong; as mmyers points out the events only fire when the selection changes.
Looking a the
JTabbedPane
code (version 6) both codes go throughremoveTabAt
, which should decrease the count. It probably will fire off an event for each tab, however, meaning that the first event should have thegetTabCount()
one less then the count before theremoveAll()
.Are you certain about the
getTabCount()
call? What happens if you remove all tabs (from the end) manually?Try to call validate or revalidate