10

I have a TabPane with closable tabs. I want to fire a "close tab event" when the user clicks a button in the content of the tab. Here is the method 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 custom 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);

Normally, the tabs can be closed by clicking the (default) close icons in the header of the tab, and "Closed!" is printed to the screen. However, when the user clicks the button (that is in the content of the tab) and calls close() method of CustomTab, again, "Closed!" is printed to the screen, but the tab is not closed this time. Isn't it weird?

How can I close a tab upon clicking on an arbitrary button?

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

4

2 回答 2

13

仅使用的方法tabPane.getTabs().remove(tab)并不完全正确,因为如果设置它不会调用“onClosed”处理程序。我正在使用以下方法:

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

如果没有设置处理程序或调用“onClosed”处理程序,则删除选项卡。

于 2014-01-09T14:29:31.960 回答
12

我为此打开了一个功能请求

同时,如果您使用的是 Java 8 并且不使用自定义 TabPane 外观,则可以使用此解决方法来模拟单击关闭按钮时发生的确切关闭行为:

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();
    }
}
于 2014-04-01T11:04:03.250 回答