英文:
JavaFX updating Cells wrong -> Bug?
问题
我在一个JavaFX应用程序中遇到了一个非常奇怪的错误。一个单元格应该根据一个布尔值进行条件格式化。然而,如果你在ListView中上下滚动,不同的条目会被以颜色高亮显示。然而,在整个列表中只有一个条目应该被标记。
serialNumberList.setCellFactory(lv -> new ListCell<ListData>() {
@Override
protected void updateItem(ListData c, boolean empty) {
super.updateItem(c, empty);
if (empty) {
setText(null);
} else {
setText(c.name);
}
System.out.println(c);
if (c != null && c.colored) {
setStyle("-fx-background-color: #33CEFF");
}
}
});
ListData
类:
String name;
boolean colored = false;
int id;
public ListData(String name, boolean colored, int id) {
this.name = name;
this.colored = colored;
this.id = id;
}
滚动前的结果:
滚动几次后的结果:
英文:
I got a very strange bug in a JavafX application. A cell should be conditionally formatted due to a boolean. If you scroll up and down the ListView, however, the various entries are highlighted in color. However, there is only one entry in the entire list that should be marked.
serialNumberList.setCellFactory(lv -> new ListCell<ListData>() {
@Override
protected void updateItem(ListData c, boolean empty) {
super.updateItem(c, empty);
if (empty) {
setText(null);
} else {
setText(c.name);
}
System.out.println(c);
if (c != null && c.colored) {
setStyle("-fx-background-color: #33CEFF");
}
}
});
The ListData
Class:
String name;
boolean colored = false;
int id;
public ListData(String name, boolean colored, int id) {
this.name = name;
this.colored = colored;
this.id= id;
}
The result before scrolling:
The result after scrolling a few times:
答案1
得分: 2
感谢 @scary-wombat 和 @kleopatra
serialNumberList.setCellFactory(lv -> new ListCell<ListData>() {
@Override
protected void updateItem(ListData c, boolean empty) {
super.updateItem(c, empty);
if (empty) {
setText(null);
} else {
setText(c.name);
}
System.out.println(c);
if (c != null && c.colored) {
setStyle("-fx-background-color: #33CEFF");
} else {
setStyle(null);
}
}
});
唯一需要做的是设置 "unstyled"
谢谢!
英文:
Thanks to @scary-wombat and to @kleopatra
serialNumberList.setCellFactory(lv -> new ListCell<ListData>() {
@Override
protected void updateItem(ListData c, boolean empty) {
super.updateItem(c, empty);
if (empty) {
setText(null);
} else {
setText(c.name);
}
System.out.println(c);
if (c != null && c.colored) {
setStyle("-fx-background-color: #33CEFF");
}
else {
setStyle(null);
}
}
});
The only thing to do was to set "unstyled"
Thanks!
答案2
得分: 1
在你的细胞工厂中,你已经定义了一个条件,可以将细胞涂成蓝色,但你还没有执行相反的操作。另外,你必须为空细胞插入一个条件。
你需要修改你的updateItem
方法的结尾:
if (c != null && !empty && c.colored)
setStyle("-fx-background-color: #33CEFF");
else
setStyle(null);
英文:
In your cell factory, you have defined a condition where you can paint your cell in blue, but you haven't done the opposite action. In addition, you must insert a condition for empty cells.
You have to modify the end of your updateItem
method:
if (c != null && !empty && c.colored)
setStyle("-fx-background-color: #33CEFF");
else
setStyle(null);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论