JavaFX动态对象的文本样式 [英] JavaFX Text styling for dynamic objects

查看:901
本文介绍了JavaFX动态对象的文本样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的计划中使用了 ListView 许多,许多样式文本的。目前,我正在做这样的事情

I'm using a ListView in my program with many, many styled Text's. Currently, I'm doing something like this

case COMMENT:
  t = new Text(lexer.comment.toString());
  t.setStyle(BASE_STYLE + COMMENT_STYLE);

其中样式存储为java字符串。我有一个 global.css 在我的应用程序,用于样式的一些静态节点的场景,但对于程序化创建的文本,我不知道如何访问。我尝试使用 t.setId(..)并在css文件中放置一个样式定义,但这不起作用。

where the style is stored as java string. I do have a global.css in my application which is used to style some static nodes of the scene, but for the programatically created texts I don't know how to access this. I tried using t.setId(..) and put a style definition in the css file but this doesn't work.

有没有办法,我可以存储所有样式为我不同的文本类型在一个CSS和访问它们很容易?请注意,我正在创建许多这些文本对象。

Is there a way that I can store all styles for my different text types in one css and access them easily? Note that I'm creating many of those text objects.

推荐答案

有三种方法可以将CSS样式应用于JavaFX节点(或其组合):

There are three ways to apply CSS styling to a JavaFX Node (or a combination of them):


  1. 正如Tom所说, Node s css样式类通过 Node.getStyleClass() 。这会返回一个ObservableList,您可以在其中添加和删除您的样式类。

  2. 如果您经常更改Nodes样式,最好使用伪选择器,例如: hover :active Node.pseudoClassStateChanged()

  3. 你已经发现的第三个选项( setStyle()),但我不喜欢这个选项,因为将CSS部分移动到一个单独的文件提供了许多优点。

  1. As Tom mentioned, a Nodes css style classes are accessed via Node.getStyleClass(). This returns an ObservableList where you can add and remove your style classes.
  2. If you change a Nodes style rather often, it is better to use pseudo selectors, like :hover or :active with Node.pseudoClassStateChanged().
  3. The third option you already discovered (setStyle()), but I dislike this option because moving the CSS parts into a seperate file offers many advantages.






对于#1和#2,您需要将样式表附加到场景/节点,并使用 Scene.getStylesheets() Parent.getStylesheets() ,您的CSS定义存储在其中。例如:


For #1 and #2 you need to attach a Stylesheet to the Scene/Node, with Scene.getStylesheets() or Parent.getStylesheets(), where your CSS definitions are stored. For example:

listView.getStylesheets().add(getClass().getResource("myStyles.css").toExternalForm());






#1的附加信息: / em>


Addtional info for #1:

如果要将样式类 my-node 添加到JavaFX节点: p>

If you want to add the style-class my-node to a JavaFX Node:

node.getStyleClass().add("my-node");

现在您可以在CSS文件中为该节点设置样式:

now you can style that node in your CSS file:

.my-node {}






#2的额外信息:

您可以声明并使用您自己的伪类, / p>

You can declare and use your own pseudo-class with

PseudoClass comment = PseudoClass.getPseudoClass("comment");
node.pseudoClassStateChanged(comment, true);
node.pseudoClassStateChanged(comment, false);

在您的css文件中:

.my-node:comment {}

这篇关于JavaFX动态对象的文本样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆