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());
});
}
I have seen many tutorials how to work with css in javaFx, but I don understand how can I solve my problem.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With