有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    In the skin of a custom control I would like to draw a triangle the size of the control, and have the triangle grow as the frame is resized.

    JavaFX的默认Caspian样式的滚动条thumb实现正是这样做的。它通过-fx shape css属性实现:

    .scroll-bar:vertical .increment-arrow {
        -fx-background-color: -fx-mark-highlight-color, -fx-mark-color;
        -fx-background-insets: 1 0 -1 0, 0;
        -fx-padding: 0.333333em 0.5em 0.0em 0.0em; /* 4 6 0 0 */
        -fx-shape: "M -3 0 L 0 4 L 3 0 z";
    }
    

    Documentation of -fx-shape是:

    An SVG path string. By specifying a shape here the region takes on that shape instead of a rectangle or rounded rectangle. The syntax of this path string.


    现在来看看你显然不相关的问题标题:

    Get the size of a Node in a given layout in javafx 2.0?

    那么你到底想要什么尺寸的

    节点的视觉边界是bounds in parent。 节点的layout bounds是:

    The rectangular bounds that should be used for layout calculations for this node. layoutBounds may differ from the visual bounds of the node and is computed differently depending on the node type.

    如果您不使用我前面提到的-fx shape css内容(对于您正在做的事情),您可能希望使用布局边界,因为您将在控件的父区域内布局三角形,并且三角形将自动继承应用于父区域的任何变换

    在将节点添加到活动场景并在节点上执行css传递之前,通常不会完全计算节点的布局。因此,您可以将侦听器添加到适当的属性(例如boundsInLocal),并在侦听器被触发时更新三角形渲染。这可以在不创建自定义控件和外观的情况下完成

    如果您选择自定义控件和外观,那么您可以覆盖控件的layoutChildren方法并在其中进行布局工作——但这是一个相当复杂的高级用例,除非您试图创建性能关键的、可重用的控件,否则这通常是不必要的