我有以下代码生成TableView
,
public class NavExample extends Application {
private final TableView<Person> table = new TableView<>();
private final ObservableList<Person> data
= FXCollections.observableArrayList(new Person("Z", "X"), new Person("A", "B"));
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setWidth(450);
stage.setHeight(550);
TableColumn firstNameCol = new TableColumn("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(
new PropertyValueFactory<>("firstName"));
TableColumn lastNameCol = new TableColumn("Last Name");
lastNameCol.setMinWidth(100);
lastNameCol.setCellValueFactory(
new PropertyValueFactory<>("lastName"));
table.getSelectionModel().setCellSelectionEnabled(true);
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
table.setItems(data);
table.getColumns().addAll(firstNameCol, lastNameCol);
table.getSelectionModel().selectFirst();
table.getFocusModel().focus(table.getSelectionModel().getSelectedIndex());
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(table);
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
}
public static class Person {
private final SimpleStringProperty firstName;
private final SimpleStringProperty lastName;
private Person(String fName, String lName) {
this.firstName = new SimpleStringProperty(fName);
this.lastName = new SimpleStringProperty(lName);
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String fName) {
firstName.set(fName);
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String fName) {
lastName.set(fName);
}
}
}
我默认使用
选择第一行table.getSelectionModel().selectFirst();
启动应用后,
导航(向上和向下键)不起作用,直到我在table
内选择。(尽管我保持专注table.getFocusModel().focus(table.getSelectionModel().getSelectedIndex());
)
此外,如果在点击&#34;向下或向上&#34;时选择了一行(按住班次),则行选择不会被保留而是保留下一行的单元格 正在被选中。
我该如何解决这个问题?
答案 0 :(得分:1)
更简单的解决方案是请求关注表本身,而不是特定的行/单元格:
table.requestFocus();
答案 1 :(得分:1)
如果使用单元格选择模式,则需要将单元格聚焦为一行,因此需要指定要聚焦的TableColumn
:
// table.getFocusModel().focus(table.getSelectionModel().getSelectedIndex());
table.getFocusModel().focus(table.getSelectionModel().getSelectedIndex(), table.getColumns().get(0));