在我的 JavaFX 应用程序中,我将 ListView 与自定义单元格一起使用。我想以不同于单击项目下方空白区域的方式处理列表项单击。我已经在整个 ListView 上设置了一个事件侦听器,但我无法确定单击了哪些项目(getSelectedItem()是null,可能是因为我的自定义单元格代码中的错误)。以下情况如何正确处理?
我的组件如下所示:
<fx:root type="javafx.scene.layout.VBox">
<Label fx:id="dayname" text="${controller.day.name}" />
<ListView fx:id="appointmentsListView" items="${controller.day.events}"
onMouseClicked="#handleAppointmentsClick" />
</fx:root>
Run Code Online (Sandbox Code Playgroud)
ListView 有自定义单元工厂,在组件构造函数中设置:
public class DayComponent extends VBox {
@FXML
private ListView<Appointment> appointmentsListView;
public DayComponent() throws IOException {
// ...
appointmentsListView.setCellFactory(l -> new AppointmentCell());
}
@FXML
public void handleAppointmentsClick(MouseEvent event) {
System.out.println(appointmentsListView.getSelectionModel()
.getSelectedItem()); // null in every case
}
}
Run Code Online (Sandbox Code Playgroud)
自定义单元格代码:
public class AppointmentCell extends ListCell<Appointment> {
@Override
protected void updateItem(Appointment item, boolean empty) {
super.updateItem(item, empty); …Run Code Online (Sandbox Code Playgroud)