Customize the appearance of each TreeItem in JavaFX using CSS to assign unique

I am looking for a way to color individual Tree Items in a treeView based on specific conditions. I found a promising answer, but unfortunately, I am struggling to implement it. You can check out the answer here.

My main obstacle is understanding how to utilize the setCellFactory method to style each TreeItem separately.

For reference, here is a snippet from my Bag class:

public class Bag {
    public String caption, assignment = "";
    Boolean eval;
    public Set<Vertex> Nodes = new HashSet<Vertex>();
    public Vector<Bag> ChildBags = new Vector<Bag>();

     @Override
    public String toString()
    {
        return assignment + " " + caption;
    }

}

In addition, I have included some CSS styles in my file:

.true{
    -fx-text-fill: #33cc00;
}
.assignment{
    -fx-text-fill: #0033cc;
}

The goal is to display the caption of all nodes with a true eval property in green and the assignment string in blue according to the toString() method.

If you have any insights on how to achieve this, please share. Thank you!

Answer №1

Customize the properties of a TreeCell by overriding the updateItem method, allowing you to adjust its appearance based on the value of the TreeItem it contains.

In this example, cells containing values with the prefix "child" are assigned a pseudoclass, while empty cells receive a black background.

TreeView<String> treeView = ...

PseudoClass childPseudoClass = PseudoClass.getPseudoClass("child");

treeView.setCellFactory(tv -> new TreeCell<String>() {

    @Override
    protected void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        if (empty || item == null) {
            // Customize for empty or null-filled cell
            pseudoClassStateChanged(childPseudoClass, false);
            setText("");
            setStyle("-fx-background-color: black;");
        } else {
            // Customize for filled cell
            pseudoClassStateChanged(childPseudoClass, item.startsWith("child"));
            setText(item);
            setStyle(null);
        }
    }

});

CSS Stylesheet

.tree-cell:child {
    -fx-background-color: red;
}

The updateItem method is triggered by the TreeView whenever the value changes, such as when a new TreeItem is linked to the cell or the value property of a TreeItem is altered.

You can also use the factory to attach listeners to the TreeCell, before it's returned, if you prefer this approach and wish to modify the cell based on the treeItemproperty.


EDIT: Different colors for text require using separate Nodes for each text section.

treeView.setCellFactory(tv -> new TreeCell<Bag>() {

    private final Text assignment;
    private final Text caption;
    private final Node graphic;

    {
        assignment = new Text();
        caption = new Text();
        assignment.getStyleClass().add("assignment");
        graphic = new HBox(4, assignment, caption);
        setGraphic(graphic);
    }

    @Override
    protected void updateItem(Bag item, boolean empty) {
        super.updateItem(item, empty);
        if (empty || item == null) {
            setGraphic(null);
        } else {
            setGraphic(graphic);
            assignment.setText(item.assignment);
            caption.setText(item.caption);
            caption.getStyleClass().remove("true");
            if (item.eval) {
                caption.getStyleClass().add("true");
            }
        }
    }

});

To color the text, utilize the -fx-fill property rather than the -fx-text-fill property.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jquery is in motion while svg paths are at a standstill, waiting to

i have been attempting to incorporate a css-animated svg into my project. initially, the animation would start automatically, which was undesirable. after some research, i discovered that by declaring it as paused and then triggering it using jQuery with $ ...

Tips for adjusting the duration of a background in jQuery

jQuery(document).ready(function(){ jQuery('div').css('background-color','#ffffff').delay(12000).css('background-color','#000000'); }); Hello everyone! I'm having some trouble with this code. I am ...

Step-by-step guide to implementing a sticky header while scrolling

How can I implement a fixed header on scroll, like the one seen on this website: www.avauntmagazine.com Here is the HTML for my header: <div class="bloc bgc-wild-blue-yonder l-bloc " id="bloc-1"> <div class="container bloc-sm"> &l ...

Trigger a click event to alter the child div elements

I have a <div> that expands when clicked and shrinks back when clicked again. Inside this div are images that should only appear once the div expands. My issue is ensuring that all images except the first one are hidden until the div expands. https: ...

Altering the hue of a picture

Looking to alter the color of an image on a webpage, specifically a carport. It's crucial that the texture and shadows remain consistent. Swapping out images with different colors would require an excessive amount of images, so I'm seeking advice ...

How to use CSS animations to remove an element from the DOM

My website has a structured HTML layout with product containers and individual products. I also have a JavaScript function that can remove any product from the page. <div class="products-container"> {foreach from=$cart.products item=product} & ...

Styling used on the ofx.com website

I am attempting to recreate the CSS effects used on ofx.com, which includes a picture of London and a grey box with text. However, my version is not working properly. I am unsure of what might be missing in my code. Here is the snippet: .generic-hero-bl ...

Implement a vertical scrolling animation in datatables

I am trying to utilize datatables to display all data. My goal is to have the data automatically scroll row by row every 3 seconds. This is my code, and you can also check it out on jsfiddle The intention is to showcase this data on a large screen. < ...

Importing CSS with Node Sass using npm

Instead of inlining css within sass, I attempted to utilize the npm package Node Sass CSS importer. Unfortunately, I am struggling to get it to function properly. I typically use npm as my build tool: "build:css": "node-sass some_path/style.scss some_pa ...

It is not possible to simultaneously utilize the properties `display: inline-block` and `width: 100%`

As someone with limited CSS knowledge, I have encountered a challenge. My goal is to ensure that my website's body has a width of 100%, while also preventing the content from wrapping when the browser window is resized. To achieve this, I attempted a ...

Troubles with CSS in Wordpress

Hey there! I'm currently working on some wordpress tasks and running into an issue with the code. Everything looks good in the first two sections, but the third section is displaying at the top. Please refer to the attached image for a visual of the p ...

Creating responsive divs on my webpage

Although I have browsed through various posts with similar questions, none of the solutions seem to work for me. I will make sure to include all relevant information related to my issue and explain why I am unable to resolve it on my own. Currently, I am ...

How to position one div next to another using CSS and HTML

Hey there, I'm facing an issue with creating a sidenav next to a div containing paragraphs and images. I can't seem to make both the sidenav and the other div appear inline. If anyone has any insights on how to solve this problem or spot what I&a ...

Searching for a comprehensive guide to web-related terminology that is widely accepted

Constantly immersing myself in studying the languages I am familiar with and exploring new development concepts and languages is a regular practice for me. When it comes to books, O'Reilly is my go-to choice, but when it comes to online resources, I&a ...

Using CSS transforms to place the vanishing point

I am attempting to utilize CSS transforms to create a flat 'floor' that extends infinitely towards the horizon. The vanishing point, where the floor disappears into the distance, should align halfway up the browser window. I have encountered an ...

Modify the body tag upon loading the page for Bootstrap 2.0

I'm currently utilizing bootstrap on my website, and I have implemented scrollspy with bootstrap. However, I am facing an issue where adding scrollspy to other pages causes my links to behave unexpectedly. Is there a way to simply incorporate the foll ...

Creating responsive CSS layouts for various device sizes

My webpage features a form with a prompt for the input box, followed by the input box itself. I want to implement two different layouts based on the device accessing the page. For cell phones, I want everything stacked vertically. However, for computers, ...

Creating a virtual roulette wheel with JavaScript

I'm currently working on creating a roulette wheel using JavaScript. While researching, I came across this example: , but I wasn't satisfied with the aesthetics. Considering that my roulette will only have a few options, I was thinking of using ...

When a button is undersized, the click event may not register

In my angular application, I have developed a directive for a tinyMCE editor. Upon setup, I have implemented two handlers: one for the blur event to hide the toolbar and another for the click event to show it. Additionally, I have created another directive ...

The unique GopikaTwo Gujarati font is unfortunately not compatible with Android mobile browsers and hybrid applications

I am currently trying to incorporate the custom font GopikaTwo into my hybrid application. Below is the code snippet I have added to my CSS file: @font-face { font-family: 'GopikaTwo' !important; src: url('GopikaTwo.eot') !impo ...