7

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.

1 Answer 1

23

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.