我在 TabPane 的选项卡之一中有一个 TableView。我想在单元格用户 id 上添加单击事件,以便当用户单击特定用户 id 时,我会打开一个包含用户特定详细信息的新选项卡。如何向列中的所有单元格添加事件监听器?
<TableView fx:controller="tableViewController"
fx:id="tableViewTable" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8">
<columnResizePolicy>
<TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
</columnResizePolicy>
<columns>
<TableColumn text="First Name">
<cellValueFactory>
<PropertyValueFactory property="firstName" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Last Name">
<cellValueFactory>
<PropertyValueFactory property="lastName" />
</cellValueFactory>
</TableColumn>
<TableColumn text="User Id">
<cellValueFactory>
<PropertyValueFactory property="userId" />
</cellValueFactory>
</TableColumn>
</columns>
</TableView>
此博客http://java-buddy.blogspot.com/2013/05/detect-mouse-click-on-javafx-tableview.html谈论以编程方式捕获点击事件,在使用 FXML 时如何做类似的事情?
最佳答案
您需要在 Controller 中执行此操作。将 fx:id
添加到表列(例如 fx:id="userIdColumn"
),然后在 Controller 中在该列上设置一个单元工厂:
public class TableViewController {
@FXML
private TableColumn<User, String> userIdColumn ;
public void initialize() {
userIdColumn.setCellFactory(tc -> {
TableCell<User, String> cell = new TableCell<User, String>() {
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty) ;
setText(empty ? null : item);
}
};
cell.setOnMouseClicked(e -> {
if (! cell.isEmpty()) {
String userId = cell.getItem();
// do something with id...
}
};
return cell ;
});
// other initialization code...
}
// other controller code...
}
这里我假设您的表显示您创建的某个User
类的对象,并且用户 ID 是一个String
。显然您可以根据需要调整类型。
关于mouseevent - 如何为Tableview中表格列的单元格设置点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35562037/