[英]How to create shape objects for Pane?
My project is creating a simple 2D ping pong game.我的项目是创建一个简单的 2D 乒乓球游戏。 I am using the Pane class, however I find it tedious to having to add the shape objects which I create to
root.getChildren().add()
method everytime.我正在使用窗格 class,但是我发现每次都必须将我创建的形状对象添加到
root.getChildren().add()
方法很乏味。 I am trying to create a function to do this but I do not know how I would call the method to add all the objects created to root.getChildren().add()
我正在尝试创建一个 function 来执行此操作,但我不知道如何调用该方法以将创建的所有对象添加到
root.getChildren().add()
Code:代码:
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.stage.Stage;
import javafx.scene.Group;
import javafx.scene.canvas.*;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
int SCREEN_WIDTH = 600;
int SCREEN_HEIGHT = 600;
//Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
Group root = new Group();
Scene scene = new Scene(root, SCREEN_WIDTH, SCREEN_HEIGHT, Color.BLACK);
Pane canvas = new Pane();
canvas.setStyle("-fx-background-color: black;");
canvas.setPrefSize(SCREEN_WIDTH,SCREEN_HEIGHT);
//Rectangle rect1 = new Rectangle(200,50,Color.BLUE);
root.getChildren().add(**drawShapes()**); // trying to call method
primaryStage.setTitle("Hello World");
primaryStage.setScene(scene);
primaryStage.show();
}
public void drawShapes() { // function I am trying to implement
Rectangle rect1 = new Rectangle(200,50,Color.BLUE);
}
}
Eg I am wanting to create a rectangle object and add it to the pane using the function to be displayed.例如,我想创建一个矩形 object 并使用要显示的 function 将其添加到窗格中。
Any help is appreciated.任何帮助表示赞赏。
You need to return your Rectagle
, like你需要返回你的
Rectagle
,比如
public void drawShapes() { // function I am trying to implement
return new Rectangle(200,50,Color.BLUE);
}
Or you can delegate the whole thing:或者你可以委托整个事情:
public void drawShapes(Group root) { // function I am trying to implement
root.getChildren().add(new Rectangle(200,50,Color.BLUE));
}
but then you will need to change the way you use drawShapes
by replacing但是你需要通过替换来改变你使用
drawShapes
的方式
root.getChildren().add(**drawShapes()**);
with和
drawShapes(root);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.