2016-10-28 109 views
0

我如何可以通過單擊列名選擇所有列, 我發現如何選擇多個列或一行,但我要的是一個點擊=所有選定這樣的形象選擇在TableView中的JavaFX

Excel exemple

當我點擊A並選擇了整個列。

+1

你能你的表視圖對象和列對象,所以我可以看到數據類型。 –

回答

0

您可以替換TableColumnHeader的事件處理程序。從這位聽衆可以使用TableView的選擇模型選擇整個列。如果你想額外的列空單元格顯示爲選中,你可以添加一個風格類所選列:

private static final String selectedStyleClass = "selected"; 

@Override 
public void start(Stage primaryStage) { 
    TableView<Item<String>> tableView = createTable(); 

    // set selection mode to multi-cell-selection 
    tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); 
    tableView.getSelectionModel().setCellSelectionEnabled(true); 

    // make sure the table skin is created 
    Scene scene = new Scene(tableView); 
    tableView.applyCss(); 
    tableView.layout(); 

    // clear column selection on change of selected cells 
    tableView.getSelectionModel().getSelectedCells().addListener((Observable v) -> clearSelections(tableView)); 

    tableView.lookupAll("TableColumnHeader").stream().forEach(h -> { 
     final TableColumnHeader header = (TableColumnHeader) h; 
     header.setOnMouseReleased(evt -> { 
      evt.consume(); 

      // select the whole column 
      tableView.getSelectionModel().selectRange(0, header.getTableColumn(), tableView.getItems().size() - 1, header.getTableColumn()); 

      // add style class for styling empty cells in selected column 
      List<String> style = header.getTableColumn().getStyleClass(); 
      if (!style.contains(selectedStyleClass)) { 
       style.add(selectedStyleClass); 
      } 
     }); 
    }); 

    scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm()); 
    primaryStage.setScene(scene); 
    primaryStage.show(); 
} 

private static void clearSelections(TableView<?> tableView) { 
    for (TableColumn column : tableView.getColumns()) { 
     column.getStyleClass().remove(selectedStyleClass); 
    } 
} 

的style.css

.table-view:focused .table-cell:empty.selected { 
    -fx-background: -fx-selection-bar; 
    -fx-table-cell-border-color: derive(-fx-selection-bar, 20%); 
} 

.table-view .table-cell:empty.selected { 
    -fx-background: -fx-selection-bar-non-focused; 
    -fx-table-cell-border-color: derive(-fx-selection-bar-non-focused, 20%); 
    -fx-background-color: -fx-table-cell-border-color, -fx-background; 
    -fx-background-insets: 0, 0 0 1 0; 
} 
+0

非常感謝 – zaki