Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

css

javafx

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.

like image 970
Ján Яabčan Avatar asked Jan 22 '16 19:01

Ján Яabčan


1 Answers

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;
}
like image 80
James_D Avatar answered Nov 09 '22 05:11

James_D