如何动态地更改项目的背景在JavaFX的列表视图 [英] How do I dynamically change the background of an item in a listview in JavaFX

查看:828
本文介绍了如何动态地更改项目的背景在JavaFX的列表视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个程序,它会将一组项目的列表视图。
然后它检查是否找到数据库中的项目。如果该项目不能在数据库中找到我想改变这个项目的背景在我的列表视图。
我使用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.

我如何做到这一点?

推荐答案

您可以使用自定义电池厂该检查的条件和适当的CSS样式类适用于每个项目/单元格ListView控件。

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.

以下code显示了如何去,对于类型为String的项目列表视图。

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;
        }
    });

在你的CSS文件中,一个可能的定义 mystyleclass 看起来是这样的(显示不可用红色背景的项目):

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;
}

这篇关于如何动态地更改项目的背景在JavaFX的列表视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆