【发布时间】:2022-03-07 14:34:02
【问题描述】:
我正在为我的测验应用程序开发一个编辑器。
我有一个自定义的ListCell<Question> 类,如下所示:
public class QuestionListCell extends ListCell<Question> {
private static final Logger LOGGER = Logger.getLogger(QuizLoader.class.getName());
@FXML HBox cellBox;
@FXML Label title;
@FXML GridPane answersGrid;
private FXMLLoader loader;
@Override
protected void updateItem(Question item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
}
else {
if (loader == null) {
loader = new FXMLLoader(getClass().getResource(QUESTION_LIST_CELL_FXML));
loader.setController(this);
try {
loader.load();
}
catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
}
}
addContent(item);
}
}
private void addContent(Question question) {
title.textProperty().bind(question.getQuestionTextProperty());
int answersSize = question.getAnswers().size();
for (int i = 0; i < answersSize; i++) {
int rowIndex = i / 2;
int colIndex = i % 2 == 0 ? 0 : 1;
Label answerLabel = new Label();
answerLabel.textProperty().bind(question.getAnswers().get(i).getAnswerTextProperty());
answerLabel.prefWidthProperty().bind(Bindings.divide(answersGrid.widthProperty(), 2));
answersGrid.add(answerLabel, colIndex, rowIndex);
}
final NumberBinding cellBoxWidth = Bindings.subtract(getListView().widthProperty(), 20);
cellBox.prefWidthProperty().bind(cellBoxWidth);
answersGrid.prefWidthProperty().bind(cellBoxWidth);
setGraphic(cellBox);
}
}
我在MainController 中设置了我的 ListView,如下所示:
@FXML
private void onAddButtonClicked() {
LOGGER.log(Level.INFO, "addButton clicked.");
// quiz.getQuestions().add(quiz.getQuestions().get(0));
}
@FXML
private void onDeleteButtonClicked() {
LOGGER.log(Level.INFO, "deleteButton clicked.");
int index = listView.getSelectionModel().getSelectedIndex();
if (index >= 0) {
quiz.getQuestions().remove(index);
}
}
private void setUpQuestionsListView() {
listView.setCellFactory(listView -> new QuestionListCell());
listView.itemsProperty().bindBidirectional(quiz.getQuestionsProperty());
}
到目前为止一切顺利,ListView 看起来像这样:
但是,当我删除第一个(并且只有第一个)项目时,第二个项目的 GridPane 似乎覆盖在第一个项目上。
据我所知,如果我在 ListView 中有更多元素,也不会发生这种情况,只有当只剩下两个元素并且我正在删除第一个元素时。我做错了什么?
【问题讨论】: