如何在场景中间获得白色矩形。我想保留自己的代码及其高度和宽度。可能应该用它来设置X和Y布局。但是我不知道怎么做。当我设置它们时,它会从左上角调整大小。
代码:
Pane paneCanvas = new Pane();
final Canvas canvas = new Canvas();
paneCanvas.setStyle("-fx-background-color: white;");
canvas.setHeight(32);
canvas.setWidth(32);
paneCanvas.getChildren().add(canvas);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
答案 0 :(得分:0)
尝试此示例...对于场景中间的位置,您可以计算此公式的宽度:
layoutxcanvas =(widthscene / 2) - (widthcanvas / 2)
layoutycanvas =(heightscene / 2) - (heightcanvas / 2)
import java.awt.Graphics2D;
import java.awt.Paint;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class JavaFXApplication1 extends Application {
@Override
public void start(Stage primaryStage) {
Pane paneCanvas = new Pane();
final Canvas canvas = new Canvas();
paneCanvas.setStyle("-fx-background-color: black;");
canvas.setHeight(32);
canvas.setWidth(32);
canvas.getGraphicsContext2D().setFill(Color.WHITE);
canvas.getGraphicsContext2D().fillRect(0, 0, 32, 32);
canvas.setLayoutX((300/2)-(32/2));
canvas.setLayoutY((300/2)-(32/2));
paneCanvas.getChildren().add(canvas);
Scene scene=new Scene(paneCanvas,300,300);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}