小编buo*_*oto的帖子

具有自定义单元格单击处理的 ListView

在我的 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)

java listview javafx event-handling

1
推荐指数
1
解决办法
4439
查看次数

标签 统计

event-handling ×1

java ×1

javafx ×1

listview ×1