Events JavaFX:如何扩展矩形并添加OnMouseClick()处理程序

Events JavaFX:如何扩展矩形并添加OnMouseClick()处理程序,events,javafx,extends,rectangles,mouseclick-event,Events,Javafx,Extends,Rectangles,Mouseclick Event,我想跟踪矩形被单击的次数。我决定扩展Rectangle类并添加一个int变量: import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; public class MyRectangle extends Rectangle{ public int clickedTimes = 0; public MyRectangle(int w, int h, Color c) { super

我想跟踪矩形被单击的次数。我决定扩展Rectangle类并添加一个int变量:

import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;

public class MyRectangle extends Rectangle{
    public int clickedTimes = 0;
    public MyRectangle(int w, int h, Color c) {
        super (w, h, c);
    }   
}
在主课堂上,我会这样做:

public class Test extends Application {

    GridPane root = new GridPane();

    @Override
    public void start(Stage primaryStage) {
        root.setVgap(1);
        root.setHgap(1);
        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);

        ColumnConstraints cc = new ColumnConstraints();
        cc.setPercentWidth(10);
        RowConstraints rc = new RowConstraints();
        rc.setPercentHeight(10);
        root.getColumnConstraints().add(cc);
        root.getRowConstraints().add(rc);
        for (int c = 0; c < 10; c++) {
            root.getColumnConstraints().add(cc);
            root.getRowConstraints().add(rc);
            for (int r = 0; r < 10; r++) {
                int w = (int) root.getWidth() / 10;
                int h = (int) root.getHeight() / 10;
                final MyRectangle rec;
                if ((r + c) % 2 == 0) {
                    rec = new MyRectangle(w, h, Color.GRAY);
                } else {
                    rec = new MyRectangle(w, h, Color.BEIGE);
                }
                ((Rectangle)rec).setOnMouseClicked(new Listner(rec)); //****QUESTION IS IN THIS LINE****
                root.add(rec, c, r);
            }
        }

        primaryStage.show();
    }
ram args the command line arguments

    public static void main(String[] args) {
        launch(args);
    }
}

问题是:为什么我必须将rec强制转换为Rectanglerec才能点击methodiod?MyRectangle应该具有原始Rectangle类中的所有方法

您是如何决定必须强制转换的?嗯,它是有线的。现在它起作用了。顺便说一下,我得到了错误消息,比如onMouseClicked,在rec中找不到。