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?
App.java
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 );
}
}
app.css
.list-cell:disabled {
-fx-background-color: #ddd;
}
See Question&Answers more detail:os