【发布时间】:2018-04-09 08:52:23
【问题描述】:
在我的 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>
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
}
}
自定义单元格代码:
public class AppointmentCell extends ListCell<Appointment> {
@Override
protected void updateItem(Appointment item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
setGraphic(new AppointmentLabel(item));
} else {
setGraphic(null);
}
}
}
【问题讨论】:
-
@James_D 我已经尝试过这种方法,但如果列表为空,这将不起作用。我也需要处理空白点击。
-
你可以指定一个自定义占位符并注册一个监听器来处理这种情况
-
这可能是一个解决方案,但我仍然希望找到更清洁的方法。
-
或者,如果单元格非空,则只需在单元格上使用鼠标处理程序中的事件,然后在列表视图上注册另一个鼠标处理程序。仅当单元鼠标处理程序未使用该事件时,才应调用该处理程序。这可能会提供一种合理的方法来将“空”功能与“非空”功能分开。
标签: java listview javafx event-handling