Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing - Knowing if tab has been removed/added in ChangeListener

Let's say I have JTabbedPane with a ChangeListener

JTabbedPane tabbedPane = new JTabbedPane();

// Add few tabs
.....
.....

tabbedPane.addChangeListener(new ChangeListener() {
  public void stateChanged(ChangeEvent changeEvent) {
    // How to determine if the changeEvent was fired because of a tab remove/add ?
  }
});

and somewhere I am doing a

tabbedPane.removeTabAt(2);

and somewhere else

tabbedPane.add(panel, 0);

The ChangeListener should get fired now, is there any way to determine within the listener if it was called due to a tab remove/add ?

EDIT: I am basically trying to do some actions only when the user switches between tabs and not when adding or removing.

like image 784
Krishnaraj Avatar asked Dec 21 '22 17:12

Krishnaraj


1 Answers

If I remember correctly, JTabbedPane will fire a componentAdded() event (defined in Container) when a new tab is added and a componentRemoved() event if a tab is removed.

You should be able to listen for adding or removal of a tab by registering a ContainerListener

http://docs.oracle.com/javase/7/docs/api/java/awt/Container.html#addContainerListener(java.awt.event.ContainerListener)

The stateChanged() event is just a side-effect of the add because the JTabbedPanel automatically switches to the new tab.

like image 130
a_horse_with_no_name Avatar answered Dec 24 '22 03:12

a_horse_with_no_name