我正在尝试构建以下矩形星形网格,其中第二行和第三行向右偏移以实现设计模式。
但是,通过我的代码,我所取得的成就是:
我的代码是:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.stage.Stage;
import java.util.Random;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
GridPane grid = new GridPane();
Random rand = new Random();
int colNum = 0;
//Shapes
for (int row = 0; row < 4; row++) {
if (row == 1 || row == 3)
colNum = 6;
else
colNum = 7;
for (int col = 0; col < colNum; col++) {
Polygon star = new Polygon(25, 0, 15, 20, 0, 20, 10, 40, 5, 60, 25, 50, 45, 60, 40, 40, 50, 20, 35, 20);
star.setFill(Color.WHITE);
star.setStroke(Color.BLACK);
GridPane.setRowIndex(star, row);
GridPane.setColumnIndex(star, col);
GridPane.setHalignment(star, HPos.RIGHT);
grid.getChildren().addAll(star);
}
}
Scene scene = new Scene(grid, 1024, 800, true);
primaryStage.setScene(scene);
primaryStage.show();
}
如何偏移第二行和第四行,使其看起来像第一张图片?
最佳答案
正如@jewelsea 所建议的,您可以使用 VBox
进行布局,使用 HBox
进行行:
public class App extends Application {
@Override
public void start(Stage stage) {
Pane row1 = createRow("0,0", "1,0", "2,0", "3,0", "4,0", "5,0", "6,0");
Pane row2 = createRow("0,1", "1,1", "2,1", "3,1", "4,1", "5,1");
Pane row3 = createRow("0,2", "1,2", "2,2", "3,2", "4,2", "5,2", "6,2");
Pane row4 = createRow("0,3", "1,3", "2,3", "3,3", "4,3", "5,3");
VBox pane = new VBox(row1, row2, row3, row4);
pane.setAlignment(Pos.CENTER);
pane.setStyle("-fx-background-color: #37474f; -fx-padding: 20;");
Scene scene = new Scene(pane);
stage.setScene(scene);
stage.show();
}
private static Pane createRow(String... texts) {
HBox pane = new HBox();
pane.setAlignment(Pos.CENTER);
Arrays.stream(texts).map(App::createStar)
.forEach(pane.getChildren()::add);
return pane;
}
private static Pane createStar(String text) {
Polygon star = new Polygon(15, 0, 30, 10, 45, 0, 45, 17.32, 60, 25.98, 45, 34.64, 45, 51.96, 30, 43.3, 15, 51.96, 15, 34.64, 0, 25.98, 15, 17.32, 15, 0);
star.setFill(Color.TRANSPARENT);
star.setStrokeWidth(2);
star.setStroke(Color.BLACK);
// Removes the small gap between rows
star.setScaleX(1.1);
star.setScaleY(1.1);
Label label = new Label(text);
label.setFont(Font.font("Arial", FontWeight.BOLD, 16));
label.setTextFill(Color.WHITE);
StackPane pane = new StackPane();
pane.getChildren().addAll(star, label);
return pane;
}
public static void main(String[] args) {
launch();
}
}
输出:
关于java - 使用第二行和第三行偏移制作矩形网格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69627263/