【问题标题】:Why is my javafx code centering all my shapes?为什么我的 javafx 代码以我所有的形状为中心?
【发布时间】:2020-08-02 22:48:18
【问题描述】:

我正在尝试自学 JavaFX,并尝试创建一个简单的笑脸图像。但是由于某种原因,我所有的形状都集中在了中心,而不是在我构建它们的 x&y 坐标上。我不知道为什么。谁能帮我弄清楚?

这是我的代码:

import javafx.*;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.stage.Stage;

public class smiley extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    public void start(Stage primaryStage) throws Exception {
        Circle head = new Circle(250, 250, 150);
        head.setFill(Color.YELLOW);
        Circle eyeL = new Circle(200, 175, 25);
        eyeL.setFill(Color.BLACK);
        Circle eyeR = new Circle(300, 175, 25);
        eyeR.setFill(Color.BLACK);
        double[] points = { 250.0, 200.0, 250.0, 275.0, 290.0, 275.0 };
        Polygon nose = new Polygon(points);
        Arc smile = new Arc(275.0, 300.0, 75.0, 50.0, 180.0, 180.0);
        smile.setStroke(Color.RED);
        smile.setFill(Color.YELLOW);

        StackPane smiley = new StackPane();
        smiley.getChildren().add(head);
        smiley.getChildren().add(eyeL);
        smiley.getChildren().add(eyeR);
        smiley.getChildren().add(nose);
        smiley.getChildren().add(smile);

        Scene scene = new Scene(smiley, 500, 500);
        primaryStage.setTitle("Smiley");
        primaryStage.setScene(scene);
        primaryStage.show();

    }

}

And this is what I wind up with

【问题讨论】:

  • A StackPane 默认情况下会将其所有子项居中。由于您想手动定位所有形状,您需要使用不管理其子元素位置的布局,例如PaneGroup。虽然我认为另一个选项是将每个形状的 managed 属性设置为 false (但我更喜欢使用适当的布局选项)。
  • 试试Pane smiley = new Pane()Pane的子类,见here

标签: javafx position shapes


【解决方案1】:

StackPane 将其子项彼此叠放。想想一堆煎饼。最后一个在顶部,第一个在底部。如果您设置边框/填充,那么孩子将被放置在这些插图的中心。此外,StackPane 将调整所有子项的大小以适应内容区域,但如果这不可能,它将把它放在中心。我认为这不是您的意图,因此请尝试使用 StackPane 继承自的 Pane 类。

Pane pane = new Pane();

【讨论】:

    猜你喜欢
    • 2020-10-09
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 2015-08-10
    相关资源
    最近更新 更多