java在JavaFX2.0中获取给定布局中的节点大小?
在自定义控件的外观中,我希望绘制一个与控件大小相同的三角形,并使三角形随着帧大小的调整而增长。我有下面的代码,但是当我调整框架的大小时,边界的大小只会增加。如何使其正确调整大小
private void update()
{
Bounds bounds = node.getBoundsInParent();
Path path = new Path();
path.getElements().add(
new MoveTo(
bounds.getWidth() / 2 + bounds.getMinX(),
bounds.getMinY()));
path.getElements().add(
new LineTo(bounds.getMaxX(), bounds.getMaxY()));
path.getElements().add(
new LineTo(bounds.getMinX(), bounds.getMaxY()));
path.setFill(Color.RED);
node.getChildren().setAll(path);
}
编辑:使用swing,我将执行以下操作。但我无法在JavaFX中使用它
public class Arrow extends JPanel
{
@Override
protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
Dimension size = getSize();
Point top = new Point(size.width/2,0);
Point bottomRight = new Point(size.width, size.height);
Point bottomLeft = new Point(0, size.height);
GeneralPath path = new GeneralPath();
path.moveTo(top.x, top.y);
path.lineTo(bottomRight.x, bottomRight.y);
path.lineTo(bottomLeft.x, bottomLeft.y);
path.lineTo(top.x, top.y);
Graphics2D g2d = (Graphics2D)graphics.create();
g2d.setColor(Color.RED);
g2d.fill(path);
g2d.dispose();
}
}
# 1 楼答案
JavaFX的默认Caspian样式的滚动条thumb实现正是这样做的。它通过-fx shape css属性实现:
Documentation of -fx-shape是:
现在来看看你显然不相关的问题标题:
那么你到底想要什么尺寸的
节点的视觉边界是bounds in parent。 节点的layout bounds是:
如果您不使用我前面提到的-fx shape css内容(对于您正在做的事情),您可能希望使用布局边界,因为您将在控件的父区域内布局三角形,并且三角形将自动继承应用于父区域的任何变换
在将节点添加到活动场景并在节点上执行css传递之前,通常不会完全计算节点的布局。因此,您可以将侦听器添加到适当的属性(例如boundsInLocal),并在侦听器被触发时更新三角形渲染。这可以在不创建自定义控件和外观的情况下完成
如果您选择自定义控件和外观,那么您可以覆盖控件的layoutChildren方法并在其中进行布局工作——但这是一个相当复杂的高级用例,除非您试图创建性能关键的、可重用的控件,否则这通常是不必要的