gpt4 book ai didi

Javafx:如何使用源文件的驱动程序文件来显示创建的形状

转载 作者:行者123 更新时间:2023-12-01 19:39:56 25 4
gpt4 key购买 nike

我正在尝试了解为我正在解决的某个问题而提供的驱动程序文件。我刚刚开始学习javafx,我尝试在驱动程序文件中创建一个形状,但是初始化、鼠标事件等的额外代码都在源文件中。我创建了一个函数,该函数返回矩形的初始化 X 和驱动程序文件中的 system.out.println,以便我知道它们已连接。然而,每当我运行驱动程序文件时,我都会看到一个空白屏幕,上面没有形状。有人可以告诉我场景/根/舞台显示做错了什么吗?

这是我的代码:

Multishape.java:

import javafx.application.Application;
import javafx.scene.Group;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;


public class Multishape extends Group {
//Declaring variables here gives them greater scope

private Rectangle rectangle;
private Circle circle;
Group root = new Group();

public Multishape (double x, double y, double len){
rectangle = new Rectangle(len, len, Color.BLUE);
rectangle.setX(x);
rectangle.setY(y);
circle = new Circle(len, Color.RED);

}

//@Override
public void start(Stage primaryStage) {
//rectangle.setOnMouseClicked(handleMouseClick);//Set mouse click handler
//circle.setOnMouseClicked(handleMouseClick);//Set mouse click handler

root.getChildren().add(rectangle);//Set initial shape.

Scene scene = new Scene(root, 500, 500);
primaryStage.setScene(scene);
primaryStage.show();
}


double getLen(){
return (rectangle.getX());
}

}

MultishapeDriver.java:

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.input.KeyEvent;
import javafx.event.EventHandler;

public class MultishapeDriver extends Application
{
public static void main(String[] args)
{
launch(args);
}

public void start(Stage stage)
{
stage.setTitle("Multishape lab");
Group root = new Group();
Multishape shape = new Multishape(320, 240, 40);
root.getChildren().add(shape);
//stage.addEventHandler(KeyEvent.KEY_TYPED, shape.getKeyHandler());

System.out.println(shape.getLen());
stage.setScene(new Scene(root, 640, 480));
stage.show();
}
}

最佳答案

您的 Multishape 是 Group 类型的容器。但在它的构造函数中,你只创建了 2 个对象,你永远不会将它们添加到你的多形状中。因此,您需要使用 getChildren().add(rectangele) 等将它们添加到您的多形状中。

您的 Multishape 构造函数将如下所示:

public Multishape (double x, double y, double len){
rectangle = new Rectangle(len, len, Color.BLUE);
rectangle.setX(x);
rectangle.setY(y);
circle = new Circle(len, Color.RED);
getChildren().add(rectangle);
getChildren().add(circle);
}

关于Javafx:如何使用源文件的驱动程序文件来显示创建的形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59182367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com