如果你打算推荐CSS,那就不用麻烦了,我知道它工作得很好,而且很容易使用,这只是出于好奇,因为我讨厌用Java编写代码时处理CSS。
JavaFX TextField对Parent进行了无向扩展,Parent有一个Node类型的子级的“不可修改”的observeList,其中一个必须是Text类型的,因此我扩展了TextField类并编写了两个方法进行检查,这个方法可以将TextField中的所有子级都取出来。
public ArrayList<Node> getAllChildren(Parent parent) {
ArrayList<Node> res = new ArrayList<Node>();
for (Node n : parent.getChildrenUnmodifiable()) {
if (n instanceof Parent) {
res.addAll(getAllChildren((Parent) n));
} else {
res.add(n);
}
}
return res;
}
public void printChildren() {
ArrayList<Node> nodes = getAllChildren(this);
System.out.println("size = "+nodes.size()+" {");
for (Node n : nodes) {
System.out.println(" "+n.getClass().getSimpleName());
}
System.out.println('}');
}
结果与预期完全一致。
size = 3 {
Path
Text
Path
}
所以我编写了这个方法来只获取Text对象。
private Text findText(Parent parent) {
for (Node n : parent.getChildrenUnmodifiable()) {
if (n instanceof Text) {
return (Text) n;
} else if (n instanceof Parent) {
Text p = findText((Parent) n);
if (p != null) {
return p;
}
}
}
return null;
}
它工作正常,并返回一个文本对象。
所以我只需要设置填充就可以了。
public void setTextFill(Paint p) {
findText(this).setFill(p);
}
但每当我尝试设置textFill时,就会出现一个RuntimeException,它说:
Text.fill : A bound value cannot be set
只为文本设置颜色有点长。
感谢您的帮助。