简体   繁体   中英

How do I dynamically change the background of an item in a listview in JavaFX

I am writing a program which places a set of items in a listview. Then it checks if it finds the items in the database. If the item can't be found in the database I want to change the background of that item in my listview. I am using JavaFX for this program.

How do i do this?

You can use a custom cell factory for the ListView that checks for the condition and applies the appropriate css style class to each item/cell.

The following code shows how to go about that for a Listview with items of type String.

     listView.setCellFactory(new Callback<ListView<String>, ListCell<String>>(){

        @Override
        public ListCell<String> call(ListView<String> p) {

            ListCell<String> cell = new ListCell<String>(){

                @Override
                protected void updateItem(String t, boolean bln) {
                    super.updateItem(t, bln);
                    if (t != null ) {
                        setText( t);

                        if (item_is_not_available){

                            if (!getStyleClass().contains("mystyleclass") {
                                getStyleClass().add("mystyleclass");
                            }

                        } else {
                            getStyleClass().remove("mystyleclass");
                        }
                    } else {
                        setText("");
                    }
                }

            };

            return cell;
        }
    });

In your css file, a possible definition of mystyleclass could look like this (displaying items that are not available with a red background):

.mystyleclass{
    -fx-background-color: #ff0000;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM