How to add class or pseudoclass programmatically to custom control in JavaFX?

末鹿安然 提交于 2020-01-04 02:42:24

问题


In JavaScript world it is often set element class to denote it's appearance, which is later defined by CSS.

Is this so in JavaFX?

For example, what if I want to color negative value in red in TableView cells? I would not code color directly, but assigned some class to a cell, like "negative" and later would color it into red with CSS.

I found PseudoClass class. Is it intended for this? It is marked "since 8", so is there any more mature API for this?


回答1:


If you want to add a style to a Node that you can toggle on and off, a PseudoClass is indeed the correct way to do it. It was indeed added in JavaFX 8.0, but that is the current stable version, so it is a mature API. Note that this creates a pseudoclass (:classname in CSS), not a "normal" class (.classname in CSS).

If you have a Node you want to style (lets call it node), you can use PseudoClass like this:

node.pseudoClassStateChanged(PseudoClass.getPseudoClass("negative"), true);

Do the same thing, except with false as the second argument, to turn it off again.



来源:https://stackoverflow.com/questions/37072514/how-to-add-class-or-pseudoclass-programmatically-to-custom-control-in-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!