我需要创建其中有空白空间的 Shape 对象。一个例子可以在下面看到:
目前,空白区域是另一个白色矩形,尽管我实际上希望它为空 - 请参阅蓝色矩形后面。那可能吗?我找不到任何解决方案来实现这种效果。这是我的代码:
package StackPaneTest;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
public class StackedPaneController extends Application
implements Initializable {
@FXML // fx:id="panelBlock"
private StackPane panelBlock; // Value injected by FXMLLoader
@FXML
private Rectangle body;
@FXML
private Rectangle redBox;
public static void main(String[] args) {
launch(args);
}
@Override // This method is called by the FXMLLoader when initialization is complete
public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
Shape newShape = Shape.subtract(body, redBox);
panelBlock.getChildren().add(0, newShape);
panelBlock.getChildren().remove(body);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("The test");
Group root = new Group();
try {
root.getChildren().add((Node) FXMLLoader.load(getClass().getResource("StackedPaneBlock.fxml")));
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
}
FXML 文件:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<?import javafx.scene.shape.*?>
<?import javafx.scene.text.*?>
<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml" fx:controller="StackPaneTest.StackedPaneController">
<children>
<StackPane fx:id="panelBlock" layoutX="136.0" layoutY="74.0" prefHeight="126.0" prefWidth="185.0">
<children>
<Rectangle fx:id="body" arcHeight="5.0" arcWidth="5.0" fill="DODGERBLUE" height="200.0" stroke="BLACK" strokeType="INSIDE" width="200.0" />
<Rectangle fx:id="redBox" arcHeight="5.0" arcWidth="5.0" fill="RED" height="48.99658203125" stroke="BLACK" strokeType="INSIDE" width="59.0" />
</children>
</StackPane>
</children>
</AnchorPane>
我的代码输出如下:
如您所见,减去的形状从原始位置移动。我真的需要用 FXML 来解决这个问题。