Okay. Так как до тех пор, пока ваша ячейка фактически получает фокус, предоставление настраиваемого TableCell
на фабрике ячеек столбца, который вы хотите по-другому, позволит вам прослушивать любое свойство TableCell
, так как вы сами определяете, что TableCell
. Ниже приведен пример того, как прослушивать focusProperty TableCell
и изменять стиль, когда это происходит.
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class MCVE3 extends Application {
@Override
public void start(Stage stage) {
TableView<ObservableList<String>> table = new TableView<ObservableList<String>>();
// I have no idea how to get focus on a cell unless you enable cell selection. It does not seem to be possible at all.
table.getSelectionModel().setCellSelectionEnabled(true);
// Initializes a column and adds it to the table.
TableColumn<ObservableList<String>, String> col = new TableColumn<ObservableList<String>, String>("Column");
col.setCellValueFactory(param -> new SimpleStringProperty(param.getValue().get(0)));
// Initializes a column and adds it to the table.
TableColumn<ObservableList<String>, String> col2 = new TableColumn<ObservableList<String>, String>("Column 2");
col2.setCellValueFactory(param -> new SimpleStringProperty(param.getValue().get(1)));
// We add a custom cell factory to second column. This enables us to customize the behaviour of the cell.
col2.setCellFactory(e -> new FocusStyleCell());
table.getColumns().addAll(col, col2);
// Add data to the table.
table.getItems().add(FXCollections.observableArrayList("One", "OneTwo"));
table.getItems().add(FXCollections.observableArrayList("Two", "TwoTwo"));
table.getItems().add(FXCollections.observableArrayList("Three", "ThreeTwo"));
table.getItems().add(FXCollections.observableArrayList("Four", "FourTwo"));
BorderPane view = new BorderPane();
view.setCenter(table);
stage.setScene(new Scene(view));
stage.show();
}
/**
* A custom TableCell that will change style on focus.
*/
class FocusStyleCell extends TableCell<ObservableList<String>, String> {
// You always need to override updateItem. It's very important that you don't forget to call super.updateItem when you do this.
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
} else {
setText(item);
}
}
public FocusStyleCell() {
// We add a listener to the focusedProperty. newValue will be true when the cell gets focused.
focusedProperty().addListener((obs, oldValue, newValue) -> {
if (newValue) {
setStyle("-fx-background-color: black;");
// // Or add some custom style class:
// if (getStyleClass().contains("focused-cell")) {
// getStyleClass().add("focused-cell");
// }
} else {
// If you instead wish to use style classes you need to
// remove that style class once focus is lost.
// getStyleClass().remove("focused-cell");
setStyle("-fx-background-color: -fx-background");
}
});
}
}
public static void main(String[] args) {
launch();
}
}
Я не уверен, я понимаю, что вы хотите от вашего примера , Вы просто хотите, чтобы стиль применялся к каждому «TableCell» всегда или только когда выбрана строка? –
Когда строка выбрана. Обычно я получаю позицию ячейки через tableView.getFocusModel(). GetFocusedCell(), но не может ее стилизовать, поскольку я не могу заставить объект TableCell применять к нему класс стиля. – gadelkareem
Итак, вы хотите создать один конкретный «TableCell» в «TableRow» при выборе «TableRow», не позволяя самому «TableCell» стать сфокусированным? –