在JavaFX开发中,建立一个自定义节点非常普遍;而且jfx中的自定义节点功能也很强大。下面我简单介绍两个自定义节点的例子。
先看代码:
class Bars extends CustomNode {
override function create():Node {
return Group {
content: for(x in [0..4]) {
Rectangle {
y: indexof x * 20
width: 100
height: 10
fill: Color.RED
}
}
};
}
}
Stage {
title: "CustomNode Basic"
width: 350
height: 200
scene: Scene {
content: [
Bars { }
]
}
}
结果显示:
jfx自定义节点实现起来比较简单,就是需要继承CustomNode,然后重写create方法。由于create方法返回的是一个节点,那么我们再使用就比较简单了,和其他jfx下的图形节点基本用法是一样的。下面我们再做一个稍微复杂点的例子。
先看代码:
var num = 10.0;
Stage {
title: "NumberBox"
width: 250
height: 280
scene: Scene {
content: VBox{
translateX: 20
translateY: 20
content: [
Slider {
min: 0
max: 100
value: bind num with inverse
}
NumberBox{
value: bind num
}
]
}
}
}
class NumberBox extends CustomNode {
public var value;
public override function create(): Node {
TextBox {
columns: 12
selectOnFocus: true
text: bind value.toString()
}
}
}
结果显示 :
这次我们在自定义节点中添加了一个公用变量value,在使用节点的时候就可以为这个变量赋值,当我们把value和滑块(Slider)中的value值相互绑定(bind)就产生了上面的效果。其实自定义节点功能很强大,在节点中还可以添加各种效果(effect)、动画、事件等等。