Get javafx TableColumn from corresponding column-header Node

别说谁变了你拦得住时间么 提交于 2019-12-24 03:30:51

问题


I'm replacing the javafx context menus of a table's columns. The context menu will give the user access to excel like filtering of the table view. Everything is working, but i now wan't to open the context menu on any mouse click event on the column header. Not just the standard right click.

The problem hereby is, that you can only get the header node by a lookupAll() inside the parent tableview. Due to the fact, that a lookup is only possible after the table view has been rendered, i call this method with a Platform.runLater(..).

TableView Class:

private void setHeaderNodesEventHandler() {
    int i = 0;
    for (final Node headerNode : lookupAll(".column-header")) {
        ((AbstractFilterableTableColumn<E, ?>) getColumns().get(i)).setHeaderNodeEventHandler(headerNode);
        i++;
    }
}

TableColumn Class:

public void setHeaderNodeEventHandler(final Node headerNode) {
    headerNode.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>(){

        @Override
        public void handle(final MouseEvent e) {
            contextMenu.show(headerNode, e.getScreenX(), e.getScreenY());
        }
    });
}

Problem here is, that i have to believe, that the order of the found headerNodes is the same as the columns. And i really don't need something bad happen here.

I would rather have something like that (see below), which is not possible, because i'm not able to cast from Parent to my AbstractFilterableTableColumn.

    private void setHeaderNodesEventHandler() {
        for (final Node headerNode : lookupAll(".column-header")) {
            final AbstractFilterableTableColumn<E, ?> column = (AbstractFilterableTableColumn<E, ?>) headerNode.getParent();
            column.setHeaderNodeEventHandler(headerNode);
        }
    }

Do you have any ideas to get the headerNodes and their respective table column without trusting the ordering?

So if anyone has a solution for my problem.. i would really appreciate it. :)


回答1:


When you create your columns, use a Label as a graphic instead of setting the text. Then you can register the mouse listener you need with the Label. I haven't tested this, but something along the following lines should work:

TableColumn<S, T> column = new TableColumn<S, T>();
Label columnHeader = new Label("Column Name");
column.setGraphic(columnHeader);

// note you can pass your TableColumn to the setHeaderNodeEventHandler(...)
// method too, so you can access the actual column represented if you need
setHeaderNodeEventHandler(columnHeader);


来源:https://stackoverflow.com/questions/25144215/get-javafx-tablecolumn-from-corresponding-column-header-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!