在JavaFX中显示字符串/标签

我需要帮助,想象一下如何在我的程序中显示文本,以便它可以在我创建的多边形形状的中间显示“停止”。 我要做的是创建一个停止标志。 我已经注意创建和显示停止标志,所以现在我只需要在t中显示“停止”

package application; public class Main extends Application { @Override public void start(Stage primaryStage) { Pane pane = new Pane(); Polygon polygon = new Polygon(); pane.getChildren().add(polygon); polygon.setFill(javafx.scene.paint.Color.RED); //sets the color of polygon ObservableList list = polygon.getPoints(); //create a label to display in the middle of the "stop sign" polygon shape //This is what I need most help on Label sign = new Label("Stop"); sign.setAlignment(Pos.CENTER); System.out.print(sign); final double WIDTH = 200, HEIGHT = 200; double centerX = WIDTH / 2, centerY = HEIGHT / 2; double radius = Math.min(WIDTH, HEIGHT) * 0.4; // Add points to the polygon list for (int i = 0; i < 6; i++){ list.add(centerX + radius * Math.cos(2 * i * Math.PI / 6)); list.add(centerY - radius * Math.sin(2 * i * Math.PI / 6)); } // Create a scene and place it in the stage Scene scene = new Scene(pane, WIDTH, HEIGHT); primaryStage.setTitle("ShowPolygon"); //Set the stage title primaryStage.setScene(scene); //Place the scene in the stage primaryStage.show(); //Display the stage } public static void main(String[] args) { launch(args); } 

}

StackPane替换Pane并向其添加sign (在多边形之后):

 public void start(Stage primaryStage) { StackPane pane = new StackPane(); Polygon polygon = new Polygon(); polygon.setFill(javafx.scene.paint.Color.RED); //sets the color of polygon ObservableList list = polygon.getPoints(); //create a label to display in the middle of the "stop sign" polygon shape //This is what I need most help on Label sign = new Label("STOP"); //sign.setStyle("-fx-text-fill: white; -fx-font-size: 3em"); sign.setAlignment(Pos.CENTER); System.out.print(sign); pane.getChildren().add(polygon); pane.getChildren().add(sign); final double WIDTH = 200, HEIGHT = 200; double centerX = WIDTH / 2, centerY = HEIGHT / 2; double radius = Math.min(WIDTH, HEIGHT) * 0.4; // Add points to the polygon list for (int i = 0; i < 6; i++) { list.add(centerX + radius * Math.cos(2 * i * Math.PI / 6)); list.add(centerY - radius * Math.sin(2 * i * Math.PI / 6)); } // Create a scene and place it in the stage Scene scene = new Scene(pane, WIDTH, HEIGHT); primaryStage.setTitle("ShowPolygon"); //Set the stage title primaryStage.setScene(scene); //Place the scene in the stage primaryStage.show(); //Display the stage } 

关于StackPane Javadoc:

StackPane以一种从后到前的堆栈展示其子项。 子项的z顺序由子列表的顺序定义,其中第0个孩子是最下面的孩子,最后一个孩子在最上面。 如果设置了边框和/或填充,则将在这些插图中布置子项。

堆栈窗口将尝试调整每个子节点的大小以填充其内容区域。 如果无法调整子项的大小以填充堆栈窗格(因为它不可resize或其最大大小阻止它),那么它将使用alignment属性在区域内对齐,该属性默认为Pos.CENTER。

只需将new Pane()更改为new StackPane()然后将您的标签添加到窗格的子列表中,就像执行Polygon一样。

StackPane是一个布局管理器,允许您将项目层叠在一起(默认情况下以分层项为中心)。