참고 : 테이블 항목과 테이블 행 사이 1 관계.
TableRow
은 보이는 항목에만 존재하며 값을 다시 할당 할 수 있습니다. 따라서 스타일 클래스를 올바르게 제거해야합니다.
또한 스타일 클래스를 사용하여 행을 표시하는 대신 더 쉽게 추가/제거 할 수있는 가상 클래스를 사용하는 것이 좋습니다.
항목 클래스의 데이터 항목에 대한 데이터를 저장하거나 적절한 외부 데이터 구조에 저장할 수 있습니다.
다음 예제에서는 ObservableMap
의 항목과 연결된 값이 변경 될 때 removed
가상 클래스를 테이블 행에 추가/제거합니다.
버튼을 사용하면 선택한 행의 가상 클래스를 할당하거나 지울 수 있습니다.
항목 대신 색인을 사용하여 비슷한 작업을 수행 할 수도 있습니다.
@Override
public void start(Stage primaryStage) {
TableView<Item> tableView = new TableView<>(FXCollections.observableArrayList(
new Item("a"),
new Item("b"),
new Item("c"),
new Item("d"),
new Item("e"),
new Item("f")
));
tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
ObservableMap<Item, Boolean> removed = FXCollections.observableHashMap();
PseudoClass removedPseudoClass = PseudoClass.getPseudoClass("removed");
tableView.setRowFactory(tv -> {
TableRow<Item> result = new TableRow<>();
ObjectBinding<Boolean> binding = Bindings.valueAt(removed, result.itemProperty());
binding.addListener((observable, oldValue, newValue) -> result.pseudoClassStateChanged(removedPseudoClass, newValue != null && newValue));
return result;
});
TableColumn<Item, String> column = new TableColumn<>("value");
column.setCellValueFactory(td -> td.getValue().valueProperty());
tableView.getColumns().add(column);
Button btn = new Button("remove");
Button btn2 = new Button("add");
btn.setOnAction(evt -> {
for (Item item : tableView.getSelectionModel().getSelectedItems()) {
removed.put(item, Boolean.TRUE);
}
});
btn2.setOnAction(evt -> {
for (Item item : tableView.getSelectionModel().getSelectedItems()) {
removed.remove(item);
}
});
Scene scene = new Scene(new VBox(10, tableView, btn, btn2));
scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
public class Item {
public Item() {
}
public Item(String value) {
this.value.set(value);
}
private final StringProperty value = new SimpleStringProperty();
public String getValue() {
return value.get();
}
public void setValue(String val) {
value.set(val);
}
public StringProperty valueProperty() {
return value;
}
}
있는 style.css
.table-row-cell:filled {
-fx-background-color: lime;
}
.table-row-cell:filled:selected {
-fx-background-color: -fx-selection-bar;
}
.table-row-cell:filled:removed {
-fx-background-color: orange;
}
.table-row-cell:filled:removed:selected {
-fx-background-color: -fx-selection-bar;
}