From d5c546a9b2717e3fdd21d61c30535209c2adbab0 Mon Sep 17 00:00:00 2001 From: Almas Baimagambetov Date: Sat, 22 Oct 2022 11:06:42 +0100 Subject: [PATCH] feat: ViewComponent.getChild() allows retrieving a specific child that is directly cast to given type --- .../fxgl/entity/components/ViewComponent.kt | 7 +++++++ .../fxgl/entity/components/ViewComponentTest.kt | 16 ++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/fxgl-entity/src/main/kotlin/com/almasb/fxgl/entity/components/ViewComponent.kt b/fxgl-entity/src/main/kotlin/com/almasb/fxgl/entity/components/ViewComponent.kt index d51417f5c2..ba827dc7e1 100644 --- a/fxgl-entity/src/main/kotlin/com/almasb/fxgl/entity/components/ViewComponent.kt +++ b/fxgl-entity/src/main/kotlin/com/almasb/fxgl/entity/components/ViewComponent.kt @@ -173,6 +173,13 @@ class ViewComponent : Component() { updatableViews += node } + /** + * @return a child node at given [index] which is then cast into [type] + */ + fun getChild(index: Int, type: Class): T { + return type.cast(children[index]) + } + /** * Remove a child from this view. */ diff --git a/fxgl-entity/src/test/kotlin/com/almasb/fxgl/entity/components/ViewComponentTest.kt b/fxgl-entity/src/test/kotlin/com/almasb/fxgl/entity/components/ViewComponentTest.kt index 27b4202611..c93d55b9c5 100644 --- a/fxgl-entity/src/test/kotlin/com/almasb/fxgl/entity/components/ViewComponentTest.kt +++ b/fxgl-entity/src/test/kotlin/com/almasb/fxgl/entity/components/ViewComponentTest.kt @@ -14,6 +14,7 @@ import javafx.scene.Node import javafx.scene.Parent import javafx.scene.input.MouseButton import javafx.scene.input.MouseEvent +import javafx.scene.shape.Circle import javafx.scene.shape.Rectangle import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat @@ -68,6 +69,21 @@ class ViewComponentTest { assertThat(rect2.parent.transforms.size, `is`(0)) } + @Test + fun `Get child with cast`() { + val rect = Rectangle() + val circle = Circle() + + view.addChild(rect) + view.addChild(circle) + + val rect2: Rectangle = view.getChild(0, Rectangle::class.java) + val circle2: Circle = view.getChild(1, Circle::class.java) + + assertThat(rect2, `is`(rect)) + assertThat(circle2, `is`(circle)) + } + @Test fun `View type children are correctly updated onUpdate and disposed on remove`() { val child = TestView()