JavaFX - dynamically close Tab in TabPane

I have a TabPane with lockable tabs. I want to fire a closed tab event when the user clicks a button in the contents of the tab. Here is the method that is called when the user clicks the button:

public class CustomTab extends Tab { ... protected void close() { Event.fireEvent(this, new Event(Tab.CLOSED_EVENT)); } .... } 

I add this user tab to tabpane as:

 TabPane tabPane = new TabPane(); ... CustomTab tab = new CustomTab(); tab.setOnClosed(new EventHandler<Event>() { @Override public void handle(Event t) { System.out.println("Closed!"); } }); tabPane.getTabs().add(tab); tabPane.getSelectionModel().select(tab); 

You can usually close tabs by clicking the close icons (the default) in the tab header and "Closed!" printed on the screen. However, when the user clicks the button (that is, in the contents of the tab) and calls the close() method of CustomTab , "Closed!" Again. printed on the screen, but this time the tab does not close. Isn't that weird?

How to close a tab when clicking on an arbitrary button?

PS: tabPane.getTabs (). remove (tab) works, but firing the corresponding event is very elegant. It should also close the tab.

+6
source share
2 answers

An approach that uses only tabPane.getTabs().remove(tab) is not entirely correct, because it does not call the onClosed handler if one is installed. I am using the following method:

 private void closeTab(Tab tab) { EventHandler<Event> handler = tab.getOnClosed(); if (null != handler) { handler.handle(null); } else { tab.getTabPane().getTabs().remove(tab); } } 

which remove the tab if the handler is not installed, or call the onClosed handler.

+9
source

I opened a function for this.

In the meantime, if you are using Java 8 and not using your own TabPane skin, you can use this workaround to mimic the exact closing behavior that occurs when you click the close button:

 import javafx.scene.control.Tab; import com.sun.javafx.scene.control.behavior.TabPaneBehavior; import com.sun.javafx.scene.control.skin.TabPaneSkin; public class MyTab extends Tab { public void requestClose() { TabPaneBehavior behavior = getBehavior(); if(behavior.canCloseTab(this)) { behavior.closeTab(this); } } private TabPaneBehavior getBehavior() { return ((TabPaneSkin) getTabPane().getSkin()).getBehavior(); } } 
+8
source

Source: https://habr.com/ru/post/947032/


All Articles