先看问题:
var rec1: Rectangle; var stage: Stage = Stage { title: "Rectangles" width: 200 height: 200 scene: Scene { content: [ VBox { spacing: 0 content: [ rec1 = Rectangle { fill: Color.BLACK width: bind stage.scene.width height: 50 } Rectangle { fill: Color.GRAY width: bind stage.scene.width height: bind stage.scene.height - rec1.height stroke: Color.BLACK } ] } ] } }
显示如下:
结果发现下面的矩形缺少了右侧和底部的描边。查看API也没有找到原因,后来做个小实验,发现原来描边操作是在原有图形的边框上添加的。
测试:
function run() { var rec1 = Rectangle { width: 140, height: 90 }; var rec2 = Rectangle { width: 140, height: 90, stroke: Color.BLACK }; println("width={rec1.width} and height={rec1.height}"); println("width={rec1.layoutBounds.width} and height={rec1.layoutBounds.height}"); println("width={rec2.width} and height={rec2.height}"); println("width={rec2.layoutBounds.width} and height={rec2.layoutBounds.height}"); }
结果:
width=140.0 and height=90.0 width=140.0 and height=90.0 width=140.0 and height=90.0 width=142.41422 and height=92.414215
注意width和layoutBounds.width的区别!
解决问题的办法:
var rec1: Rectangle; var tmp1 = Rectangle { stroke: Color.BLACK }; var tmp2 = Rectangle { }; var gap = tmp1.layoutBounds.width-tmp2.layoutBounds.width; var stage: Stage = Stage { title: "Rectangles" width: 200 height: 200 scene: Scene { content: [ VBox { spacing: 0 content: [ rec1 = Rectangle { fill: Color.BLACK width: bind stage.scene.width height: 50 } Rectangle { fill: Color.GRAY width: bind stage.scene.width - gap height: bind stage.scene.height - rec1.layoutBounds.height - gap stroke: Color.BLACK } ] } ] } }
显示如下:
问题是解决了,但是总感觉哪里有些别扭,难道JavaFX就没有相关的常量来记录这个差距吗?或者有其他的办法来解决这个问题,期待更好的解决办法。