java 是否可以在 javaFx 中为 Node 对象添加 css 类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34954141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is possible to add css class for a Node object in javaFx?
提问by Ján Яab?an
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:
我想制作一个带有可拖动节点的窗格。当我选择某个节点时,我想为该节点绘制一些边框。实际上,我已经完成了,但我的问题是,我的解决方案从 Node.js 中删除了所有其他样式。这是非常丑陋的解决方案。我想通过添加 css 类来做到这一点,但我绝对不知道该怎么做。当节点的焦点丢失时,我想删除 css 类。我是 JavaFx 的新手。我的代码如下:
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.
我看过很多关于如何在 javaFx 中使用 css 的教程,但我不明白如何解决我的问题。
回答by James_D
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:
现在你可以定义一个外部 CSS 文件:
.draggable {
/* styles for all draggable nodes */
}
.draggable:selected {
-fx-border-width: 2;
-fx-border-color: gray;
-fx-border-style: solid;
}