如何在 javafx 中获取单元格的列标题和第一列行值
How to get the column title and first column row value for a cell in javafx
我有动态创建的 JavaFX tableview。当 tableview 上的一个单元格上有一个 double-clicks 时,我需要获取该单元格所在列的名称以及该单元格所在行中第一个单元格的值。我尝试搜索 google 并没有找到解决这个问题的特别方法。请给我一些示例代码。
好的,首先,假设您的 TableView 已附加到模型:
public TableView<MyModel> myTable;
其中 MyModel 类似于:
public class MyModel {
private Integer id;
private String name;
// ... etc.
}
所以,MyModel 是一个普通的 POJO。您可以将 TableView 的列设置为:
TableColumn<MyModel, Integer> id = new TableColumn<>("ID");
id.setCellValueFactory(new PropertyValueFactory<>("id"));
TableColumn<MyModel, String> name = new TableColumn<>("Name");
name.setCellValueFactory(new PropertyValueFactory<>("name"));
然后,将列添加到您的 table:
myTable.getColumns().addAll(id, name);
现在,让我们使用 rowFactory 监听点击事件:
myTable.setRowFactory(tv -> {
TableRow<MyModel> row = new TableRow<>();
row.setOnMouseClicked(event -> {
// check for non-empty rows, double-click with the primary button of the mouse
if (!row.isEmpty() && event.getClickCount() == 2 && event.getButton() == MouseButton.PRIMARY) {
MyModel element = row.getItem();
// now you can do whatever you want with the myModel variable.
System.out.println(element);
}
});
return row ;
});
这应该可以完成工作。
我有动态创建的 JavaFX tableview。当 tableview 上的一个单元格上有一个 double-clicks 时,我需要获取该单元格所在列的名称以及该单元格所在行中第一个单元格的值。我尝试搜索 google 并没有找到解决这个问题的特别方法。请给我一些示例代码。
好的,首先,假设您的 TableView 已附加到模型:
public TableView<MyModel> myTable;
其中 MyModel 类似于:
public class MyModel {
private Integer id;
private String name;
// ... etc.
}
所以,MyModel 是一个普通的 POJO。您可以将 TableView 的列设置为:
TableColumn<MyModel, Integer> id = new TableColumn<>("ID");
id.setCellValueFactory(new PropertyValueFactory<>("id"));
TableColumn<MyModel, String> name = new TableColumn<>("Name");
name.setCellValueFactory(new PropertyValueFactory<>("name"));
然后,将列添加到您的 table:
myTable.getColumns().addAll(id, name);
现在,让我们使用 rowFactory 监听点击事件:
myTable.setRowFactory(tv -> {
TableRow<MyModel> row = new TableRow<>();
row.setOnMouseClicked(event -> {
// check for non-empty rows, double-click with the primary button of the mouse
if (!row.isEmpty() && event.getClickCount() == 2 && event.getButton() == MouseButton.PRIMARY) {
MyModel element = row.getItem();
// now you can do whatever you want with the myModel variable.
System.out.println(element);
}
});
return row ;
});
这应该可以完成工作。