JavaFX - Get TableView column by name
Asked Answered
R

3

5

Is there a way to get a column from a TableView by name?

When I need to get a column I have to get it by index:

tableView.getColumns().get(i);

but I would like to get the column by name:

tableView.getColumns().get("Column Name");
Romano answered 21/4, 2014 at 0:30 Comment(0)
W
10

It's hard to envision a situation in which you couldn't just keep references to your columns, but you can always write a method like

private <T> TableColumn<T, ?> getTableColumnByName(TableView<T> tableView, String name) {
    for (TableColumn<T, ?> col : tableView.getColumns())
        if (col.getText().equals(name)) return col ;
    return null ;
}
Woozy answered 21/4, 2014 at 0:42 Comment(2)
Yes, I could keep references to columns in a HashMap, but I was wondering if there was something in the API to get them by name.Romano
No, nothing in the API. I suspect it's just not a common enough use case; in the vast majority of cases the columns are completely static, so you would have actual named references and not even the need for a Map.Woozy
S
1

Another way of getting the column name or title is setting an ID to the column and retrieve it when necessary:

  private String col_ID = "Customer";
  private TableColumn col = new TableColumn (col_ID);
  col.setId(col_ID);

  System.out.println(col.getId());
Shampoo answered 5/11, 2017 at 12:32 Comment(0)
C
0

Working on a project and facing the same issue

@FXML

TableColumn nameOfTableColumn;

if you pass in nameofTableColumn.getText(), you will return the name of the column (nameOfTableColumn in this case). Add this code accordingly and set a breakpoint on the same line. Step into and hit the +bar over the name of your respective column: one of the exposed fields will give you the value for the column which again, in this case will be "nameOfTableColumn".

Comfrey answered 1/9, 2020 at 19:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.