我正在使用javaFX,我想从一个单独的玩家类向游戏根目录添加Rectangle对象。为此,我在游戏中创建了一个getRoot函数,并尝试从播放器类中添加矩形。尽管出于某种原因它只是起作用了。
public class Test {
public void run() {
System.out.println("loaded");
GameScene gameScene = new GameScene();
gameScene.getRoot().getChildren().add(new Sprite(50,50,50,50, Color.GREEN,"TEST", 1, 0));
}
}
public class GameScene {
private Group root = new Group();
public Scene getScene(){
Scene scene = new Scene(root, Color.BLACK);
Test test = new Test();
test.run();
return scene;
}
public Group getRoot() {
return root;
}
}
运行“ gameScene”仍然是空的,尽管“已加载”字符串已打印到控制台。
答案 0 :(得分:2)
尝试通过其他类修改根目录:
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class GameScene extends Application {
private Group root;
@Override
public void start(Stage stage) {
root = new Group();
stage.setScene(getScene());
stage.show();
}
public Scene getScene(){
Scene scene = new Scene(root);
Test test = new Test();
test.run(root);
return scene;
}
public static void main(String[] args) {
launch(args);
}
}
class Test {
public void run(Group root) {
root.getChildren().add(new Rectangle(50, 50, Color.BLACK));
}
}