在JavaFX中获取Shape对象的宽度和高度

Gre*_*989 2 java geometry 2d javafx

我有需要的任何子类的方法Shape(可以是Circle,Rectangle,Polygon,Line,等...),并返回一个Shape对象.

public Shape returnShapeObject() {
   return circle1;
}
Run Code Online (Sandbox Code Playgroud)

问题是,一旦我得到了我的圆的形状对象表示,它就不再有.getRadius()方法了.它没有.getWidth().getHeight()任何一个.

如何在2d JavaFX中获取Shape对象的半径/宽度/高度呢?

Ulu*_*Biy 5

您可以使用以下方法Node#getLayoutBounds():

List<Shape> shapes = new ArrayList<>();
shapes.add(new Circle(30));
shapes.add(new Rectangle(200, 200));
shapes.add(new Text("some arbitrary long text for testing"));
for (Shape shape : shapes) {
    System.out.println("bounds = " + shape.getLayoutBounds());
    System.out.println("width  = " + shape.getLayoutBounds().getWidth());
    System.out.println("height = " + shape.getLayoutBounds().getHeight());
}
Run Code Online (Sandbox Code Playgroud)

请注意仔细阅读该方法的javadoc.

如果你想要一个具体形状的方法和属性,那么你应该在他的评论中提到的@AKS.