2014-03-26 48 views
2

我有需要的Shape任何亞類的方法(可爲可CircleRectanglePolygonLine,等...),並返回一個Shape對象。獲取Shape對象的寬度和高度的JavaFX

public Shape returnShapeObject() { 
    return circle1; 
} 

的問題是,一旦我得到我的圓的形狀對象表示,它不再有一個.getRadius()方法。它沒有.getWidth().getHeight()

那麼我怎樣才能獲得2d JavaFX中Shape對象的半徑/寬度/高度呢?

+0

'Shape'是一個'abstract'類,它沒有像'Circle'這樣的擴展類中定義的函數。如果你想使用特定的方法,你需要將'shape'對象例如對於'Circle',你可以使用'((Circle)shape).getRadius();'和'Shape'的其他子類。 – AKS

回答

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()); 
} 

被告誡要仔細閱讀方法的javadoc。

如果你想要一個具體形狀的方法和屬性,那麼你應該做他的評論中提到的@AKS。