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

Issue with relative input causing Jquery click event to not fire

Jquery $(document).on("click","[type=text]",function(event) { alert('test'); }); CSS .noWorking:focus{ z-index:100; position:relative; outline:none; box-shadow:0 0 0 1000px rgba(0,0,0,.2); } To ensure the shadow appears on top of all oth ...

Want to learn how to center a webpage only for a specific device width? For example, have your mobile device display the content in the center, while

Hello! I'm new to the world of @media queries and am currently trying to make my webpage responsive by centering it on smaller devices while keeping the display normal on larger screens. My website, mastercontrolunit.com, looks great in deskto ...

Tips for aligning text to the left within a Bootstrap accordion

I am in the process of developing a static website utilizing the W3schools "Company" theme. The complete code for this website, including CSS, is provided below: <!DOCTYPE html> <html lang="en"> <head> <!-- Theme Made By www.w3schoo ...

Managing the layout with React Native Flexbox to evenly distribute items

Check out this React Native Demo I put together featuring Santa images being added and removed in a Flexbox. Bunch of Santas I noticed that when there are more than 3 Santas, the layout shifts to the left. I'm curious about how to keep the Santas ce ...

The CSS table-cell element causes adjacent table-cell content to reposition

The table inside the "center" div is causing the contents in the "left" div to be offset by a few pixels from the top (about 8 in my browser). When you add some text before the table, this offset disappears. Why is this happening? Is there a way to preven ...

Designing an interactive HTML table that adapts to various screen

Currently utilizing Bootstrap to create a responsive HTML table on smaller devices like the iPad, but seeking a more polished and professional alternative. Searching for a JQuery/JavaScript or CSS solution without relying on plugins. Would appreciate any ...

Getting the location of a mouse click and adding tags (marks) on an image: a simple guide

Is there a way to incorporate images with tagged marks similar to Facebook's image tagging feature? How can I retrieve the X and Y coordinates of tags on the image itself (not the screen) and display them in a responsive manner? ...

Utilize the scrollIntoView method within a jQuery function

My current setup involves using JQuery's show and hide function. Essentially, when an image is clicked, it triggers the display of an information log. The issue I am facing is that this log opens at the top of the page, whereas I would like it to scro ...

Why do my tablet media queries take precedence over mobile view media queries?

I've noticed that when I view my website on mobile devices, the tablet media queries always seem to override my mobile media queries. Can anyone explain why this is happening? Here is how I have set it up: /* X-Small devices (portrait phones, less t ...

How can JavaScript be used to rearrange the placement of DOM elements?

<!DOCTYPE html> <html> <head> <title></title> </head> <body> <div class="boxes"> <div class="red" style="width: 300px; height: 300px; color: red"></div> <div class="blue ...

Is it possible to align two buttons side by side on a webpage using only HTML and CSS?

Can you help me figure out how to align two buttons next to each other with some space between them using only css and html? If you take a look at my html code and css code, you'll see that the two buttons are not aligned properly. * { margin: 0 ...

Settings for the packaging of web components

Is there a way to configure a web component in vue.config.js and separate the iconfont.css section when building? I am using the vue-cli-service build --target wc-async --name chat-ui src/views/Chat/Launcher.vue --report command to package the web compon ...

What methods can we use to transform Bootstrap rows and columns to resemble a table design?

Attempt number one did not work due to padding issues in the columns. Attempt number two also failed, leading me to believe I may be making a mistake somewhere. This is what I am aiming for: Can anyone provide some assistance? I would prefer avoiding mo ...

The font size appears significantly smaller than expected when using wkhtmltoimage to render

I am trying to convert text into an image, with a static layout and size while adjusting the font size based on the amount of text. I prefer using wkhtmltoimage 0.12.5 as it offers various CSS styling options. Currently, I am working on a Mac. Below is a ...

Revolutionizing Interaction: Unveiling the Power of Bootstrap 3

Would you be able to assist me in customizing buttons to resemble a typical dropdown link? <div class="dropdown"> <button class="btn dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown">Dropdown <span class="caret"&g ...

CSS: Containers displayed side by side when screen width is above a certain threshold, otherwise stacked on top of each other

I am trying to make two containers responsive without using media queries or JavaScript. When the screen size is 500px or less, I want the containers to stack on top of each other and take up 100% of the screen width. But when the screen size exceeds 500 ...

CLS notifies about an Unrecognized CSS Element in Page Insights' Core Web Performance

My experience with Google PageSpeed Insights has been quite frustrating due to the numerous alerts I'm receiving about Unsupported CSS Properties. The importance of avoiding non-composited animations: Animations that are not composited can appear gli ...

Tips for breaking out of an infinite loop while loading HTML containing a carousel into a blank <div> within another HTML file using jQuery's $(document).ready() function

Currently, I am studying HTML, CSS, Bootstrap 4, jQuery3, and JavaScript (ES6+), and to enhance my skills, I have devised an exercise for practice and consolidation. I have created 4 HTML files, all featuring responsive design based on Bootstrap 4: inde ...

Different CSS values can be applied for specific versions of Internet Explorer by using conditional comments

I am dealing with a CSS class named "myclass" that requires a z-index of 5 specifically for IE8. I have attempted to achieve this using the following methods: .myclass{ z-index: 5\9; } ---> Interestingly, this method applies from IE10 onwards and ...

Is it possible to modify the button icon on hover by utilizing chakra-ui and vanilla-extract?

My stack includes nextjs13, chakra-ui, and vanilla-extract Seeking guidance on how to update both icon and text within a button upon hover, utilizing chakra-ui and vanilla-extract. The current setup of my button is as follows: <Button > <svg wi ...