【发布时间】:2020-11-22 17:13:23
【问题描述】:
我正在用 Javafx 做一个简单的类似国际象棋的游戏。 从我的开始课程开始,我成功地使用了另一个类“UIBuilder”来修改“Stage primaryStage”。我的 UIBuilder 方法创建一个场景,添加一个 GridPane,并用节点(ImageView 图片,但这应该是任意的)填充 GridPane。
这是我的“UIBuilder”构造函数的代码,这 100% 用于创建舞台、显示节点等。
我正在尝试向 UIBuilder 类添加一个方法,我可以从我的起始类启动该方法。我要做的就是更改静态 GridPane rootGrid 的特定节点。例如,如果 rootGrid 是一个 8x8 的图像网格,例如国际象棋,我希望 7,7 中的节点到一个按钮来代替图像。我知道使用静态节点可能不是最佳实践,但我试图在 100% 担心小细节之前掌握基本的 gui 创建。考虑到节点是静态的,我特别困惑。任何关于跨类使用 JavaFX 的一般建议都会有所帮助。我已经检查了 8 页的 StackOverflow 并没有遇到这个问题。感谢您的耐心等待。
我尝试将静态 GridPane rootGrid 返回到主类,然后使用 GridPane 根 = UIBuilder.getGrid() root.add(arbitraryButton, 7, 7);
我也尝试过简单地使用 UIBuilder 类中的方法来简单地创建一个按钮并将其添加到静态 gridPane rootGrid。为此,我尝试使用 UIBuilder 中的 getter 传递 Scene 和 GridPane,我想也许我可以将它们传递回 UIBuilder,然后添加一个按钮。
public static void buttonTest(Scene testScene, GridPane passGrid) {
Button testButton = new Button("Test");
passGrid.add(testButton, 8, 8);
}
Class variables
public static Stage cosmos;
public static GridPane rootGrid;
public static Scene rootScene;
public static String testString;
public static Button returnButton;
UIBuilder(Stage mainStage) {
GridPane rootGrid = new GridPane();
Scene scene = new Scene(rootGrid,1000,1600);
rootScene = scene;
mainStage.setScene(scene);
mainStage.show();
stageTestSize(mainStage, rootGrid);
rootGrid.setVgap(15);
rootGrid.setHgap(15);
randomUnits(rootGrid);
}
在我的 start 方法下,下面的构造函数引用了上面的代码并且可以完美运行。
UIBuilder uiMaster = new UIBuilder(primaryStage);
Scene exampleScene = UIBuilder.getScene();
GridPane exampleGrid = uiMaster.getGrid();
【问题讨论】:
-
minimal reproducible example 请..不要使用静态范围
-
为什么都是
static?