问题描述
我尝试使用自定义ListCell在ListView中查看自定义对象。作为演示问题的示例,我选择 java.util.File
。出于演示目的,我在渲染时直接禁用ListCell。这些项目由线程模拟的外部进程添加。一切看起来都不错,直到我将CSS着色为禁用的ListCell。现在似乎有一些幽灵物品与它们被创建的ListCell一起被禁用。
I try to view a custom object in a ListView using a custom ListCell. As an example to demonstrate the problem I chose java.util.File
. Also for demonstration purpose I disable the ListCell directly when rendered. The items are added by an external process simulated by the thread. Everything looks nice until I apply the CSS coloring the disabled ListCell. Now it seems that there are some ghost items which get disabled together with the ListCell they are created of.
我该如何解决这个问题?
How can I solve this?
public class App extends Application
{
@Override
public void start( Stage primaryStage )
{
final ListView<File> listView = new ListView<>();
listView.setCellFactory( column -> {
return new ListCell<File>()
{
protected void updateItem( File item, boolean empty )
{
super.updateItem( item, empty );
if( item == null || empty )
{
setGraphic( null );
return;
}
setDisable( true );
setGraphic( new TextField( item.getName() ) );
}
};
});
new Thread( () -> {
for( int i=0 ; i<10 ; ++i )
{
try
{
Thread.sleep( 1000 );
}
catch( Exception e )
{
e.printStackTrace();
}
final int n = i;
Platform.runLater( () -> {
listView.getItems().add( new File( Character.toString( (char)( (int) 'a' + n ) ) ) );
});
}
}).start();
Scene scene = new Scene( listView );
scene.getStylesheets().add( "app.css" );
primaryStage.setScene( scene );
primaryStage.show();
}
@Override
public void stop() throws Exception
{
super.stop();
}
public static void main( String[] args ) throws Exception
{
launch( args );
}
}
.list-cell:disabled {
-fx-background-color: #ddd;
}
推荐答案
你永远不会设置禁用
属性返回 false
。您需要为空单元格执行此操作。以下情况可能发生在 Cell
:
You never set the disable
property back to false
. You need to do this for empty cells. The following could happen to a Cell
:
- 一个项目被添加到
单元格
并且单元格已禁用 - 该项目已从
单元格
中移除,Cell
变为空,但仍保持禁用状态。
- a item is added to the
Cell
and the cell is disabled - the item is removed from the
Cell
, theCell
becomes empty, but it remains disabled.
一般情况下, Cell
变为空,当添加项目时对 Cell
所做的任何更改都应该撤消。
In general when a Cell
becomes empty, any changes done to the Cell
when an item was added should be undone.
此外,每次将新项目分配给 Cell $时,都应避免重新创建
TextField
c $ c>。
Furthermore you should avoid recreating the TextField
s every time a new item is assigned to a Cell
.
listView.setCellFactory(column -> {
return new ListCell<File>() {
private final TextField textField = new TextField();
protected void updateItem(File item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setDisable(false);
setGraphic(null);
} else {
setDisable(true);
textField.setText(item.getName());
setGraphic(textField);
}
}
};
});
这篇关于带有自定义ListCell的javafx ListView中的Ghost项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!