Home > Mobile >  tabPane.getTabs().remove(tab) doesn't call listener
tabPane.getTabs().remove(tab) doesn't call listener

Time:04-24

I have been reading this stackoverflow post. And they say tabPane.getTabs().remove(tab) will not trigger the listener on the event closing the tab which makes sense.

Therefore, I have applied their solution to my problem (I understand the principle, but not really the code), but my listener will never get called. Neither tabPane.getTabs().remove(tab) nor closeTab(tab) with the method closeTab defined like so:

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

call my listener. My listener is however called when I do close the tab with the mouse.

Here is my listener:

private static void addListenerOnClosingTab(Tab tab) {
        tab.setOnCloseRequest(new EventHandler<Event>()
        {
            @Override
            public void handle(Event arg0)
            {
                Util.loggerControllerDiagram.info("Tab "   tab.getText()   " closed.");
            }
        });
    }

CodePudding user response:

None of these approaches (in other current answers in this post, or in the original post you linked) really make sense to me. It's possible I am not understanding what you are trying to do.

If you want to respond to a tab being removed, whether it is removed by the user clicking the tab close button, or programmatically by manipulating the tab pane's list of tabs, the usual approach would be to register a listener with the list of tabs:

private TabPane tabPane ;

// ...

tabPane.getTabs().addListener((Change<? extends Tab> c) -> {
    while (c.hasNext()) {
        if (c.wasRemoved()) {
            for (Tab tab : c.getRemoved()) {
                System.out.println("Tab "   tab.getText()   " closed.");
            }
        }
    }
});

CodePudding user response:

You might want to use getOnCloseRequest instead of getOnClosed in your method closeTab:

EventHandler<Event> handler = tab.getOnCloseRequest();
handler.handle(null);
tab.getTabPane().getTabs().remove(tab);
  • Related