【发布时间】: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();
}
}
【问题讨论】:
-
A
StackPane默认情况下会将其所有子项居中。由于您想手动定位所有形状,您需要使用不管理其子元素位置的布局,例如Pane或Group。虽然我认为另一个选项是将每个形状的managed属性设置为false(但我更喜欢使用适当的布局选项)。 -
试试
Pane smiley = new Pane()或Pane的子类,见here。