Is possible to add css class for a Node object in javaFx?

16,157

Use a CSS Pseudoclass.

Give all the nodes you are going to drag some fixed style class:

private static final String DRAGGABLE_CLASS = "draggable" ;

// ...

Node node = ... ;
node.getStyleClass().add(DRAGGABLE_CLASS);

Now define a "selected" pseudoclass:

private static final PseudoClass SELECTED_PSEUDO_CLASS =
    PseudoClass.getPseudoClass("selected");

And then do:

public void addSelectionControlToNode(Node node) {
    node.addEventFilter(MouseEvent.MOUSE_CLICKED, (MouseEvent e) -> {
        if (e.isControlDown()) {
            if (selection.contains(node)) {
                selection.remove(node);
                node.pseudoClassStateChanged(SELECTED_PSEUDO_CLASS, false);
            } else {
                selection.add(node);
                node.pseudoClassStateChanged(SELECTED_PSEUDO_CLASS, true);
            }
        } else {
            selection.clear();
            selection.add(node);
            node.pseudoClassStateChanged(SELECTED_PSEUDO_CLASS, true);
        }
        System.out.println(selection.size());
    });
}

Now you can define an external CSS file with:

.draggable {
    /* styles for all draggable nodes */
}
.draggable:selected {
    -fx-border-width: 2;
    -fx-border-color: gray; 
    -fx-border-style: solid;
}
Share:
16,157
Ján Яabčan
Author by

Ján Яabčan

Updated on June 12, 2022

Comments

  • Ján Яabčan
    Ján Яabčan almost 2 years

    I want to make a pane with draggable Nodes. When I selected some node, I want to paint some border for this node. Actually, I have it done, but my trouble is, that my solution remove all another styles from Node. It is very ugly solution. I want to do it with adding css classes, but i absolutely don't know how to do it. When the focus for the node is lost, I want to remove css class. I am new to JavaFx. My code is below:

    public void addSelectionControlToNode(Node node) {
    node.addEventFilter(MouseEvent.MOUSE_CLICKED, (MouseEvent e) -> {
        if (e.isControlDown()) {
            if (selection.contains(node)) {
                selection.remove(node);
            } else {
                selection.add(node);
                //problematic area below
                node.setStyle("-fx-border-width: 2;
                   -fx-border-color: gray; -fx-border-style: solid;");
               //problematic area end
            }
        } else {
            selection.clear();
            selection.add(node);
        }
        System.out.println(selection.size());
    });
    

    }

    enter image description here

    I have seen many tutorials how to work with css in javaFx, but I don understand how can I solve my problem.