有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaFX。带样式单元格的ListView显示重复列表(Java)

我在大学里使用JavaFX进行一个简单的项目。 我必须创建一个包含两列的视图,在左侧我们可以选择一门课程,在右侧,我们可以看到学生当前订阅了该课程

对于这一切工作正常,然后我必须使ListView的单元格的背景颜色不同于选定的单元格

为了实现这一点,我扩展了类'ListCell<;T>;'创建以下内容

public class StyledSelectableCell<T> extends ListCell<T> {
    private Background selBG;
    private Background idleBG;
    private Paint idleTextCol;
    private Paint selTextCol;

    public StyledSelectableCell(Colors idleBG) {
        assert idleBG.getComplementary() != null;
        this.selBG = new Background(new BackgroundFill(idleBG.getComplementary().getVal(), CornerRadii.EMPTY, Insets.EMPTY));
        this.idleBG = new Background(new BackgroundFill(idleBG.getVal(), CornerRadii.EMPTY, Insets.EMPTY));

        this.idleTextCol = idleBG.getSuggestedTextColor();
        this.selTextCol = idleBG.getComplementary().getSuggestedTextColor();
    }

    @Override
    protected void updateItem(T item, boolean empty) {
        super.updateItem(item, empty);

        if(item == null) return;

        if(this.isSelected()) {
            setBG(this.selBG);
            setTextFill(this.selTextCol);
        }
        else {
            setBG(this.idleBG);
            setTextFill(this.idleTextCol);
        }

        setText(item.toString());
    }

    private void setBG(Background c){
        this.setBackground(c);
    }
}

然后,在主应用程序类中,我包含了以下代码:

// Creating 2 observable lists
        ObservableList<Student> studentList = FXCollections.observableArrayList();
        ObservableList<Course> courseList = FXCollections.observableArrayList(courses);

        // Creating listview for stuxents and courses
        ListView<Course> courseLv = new ListView<>(courseList);
        ListView<Student> studentLv = new ListView<>(studentList);


        // Setting custom colored cells
        // TODO bug only present with this two methods uncommented
        courseLv.setCellFactory(
                courseListView -> new StyledSelectableCell<>(STUD_COL)
        );

        studentLv.setCellFactory(
                studentListView -> new StyledSelectableCell<>(COUR_COL)
        );

        VBox studentSelection = new VBox();
        studentSelection.getChildren().add(studentLv);

        VBox courseSelection = new VBox();
        courseSelection.getChildren().add(courseLv);

        GridPane pane = new GridPane();
        pane.addColumn(1, studentSelection);
        pane.addColumn(0, courseSelection);

        courseLv.getSelectionModel().selectedItemProperty().addListener((observableValue, course, t1) -> {
            studentList.clear();
            studentList.addAll(t1.getStudents());
        });

当我启动程序时,一切正常,我点击第一门课程,学生们正确地出现。 问题是在我选择另一门课程的第二次点击时,它会显示学生在最后以相反的顺序重复两次(真奇怪)

此图显示了第一次单击时的情况: https://imgur.com/WPIEfnp

这是当我选择另一个课程时出现的错误: https://imgur.com/a/VWRp8sQ


共 (0) 个答案