Skip to content

Commit d5c546a

Browse files
committed
feat: ViewComponent.getChild() allows retrieving a specific child that is directly cast to given type
1 parent 3828786 commit d5c546a

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

fxgl-entity/src/main/kotlin/com/almasb/fxgl/entity/components/ViewComponent.kt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,13 @@ class ViewComponent : Component() {
173173
updatableViews += node
174174
}
175175

176+
/**
177+
* @return a child node at given [index] which is then cast into [type]
178+
*/
179+
fun <T : Node> getChild(index: Int, type: Class<T>): T {
180+
return type.cast(children[index])
181+
}
182+
176183
/**
177184
* Remove a child from this view.
178185
*/

fxgl-entity/src/test/kotlin/com/almasb/fxgl/entity/components/ViewComponentTest.kt

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import javafx.scene.Node
1414
import javafx.scene.Parent
1515
import javafx.scene.input.MouseButton
1616
import javafx.scene.input.MouseEvent
17+
import javafx.scene.shape.Circle
1718
import javafx.scene.shape.Rectangle
1819
import org.hamcrest.CoreMatchers.`is`
1920
import org.hamcrest.MatcherAssert.assertThat
@@ -68,6 +69,21 @@ class ViewComponentTest {
6869
assertThat(rect2.parent.transforms.size, `is`(0))
6970
}
7071

72+
@Test
73+
fun `Get child with cast`() {
74+
val rect = Rectangle()
75+
val circle = Circle()
76+
77+
view.addChild(rect)
78+
view.addChild(circle)
79+
80+
val rect2: Rectangle = view.getChild(0, Rectangle::class.java)
81+
val circle2: Circle = view.getChild(1, Circle::class.java)
82+
83+
assertThat(rect2, `is`(rect))
84+
assertThat(circle2, `is`(circle))
85+
}
86+
7187
@Test
7288
fun `View type children are correctly updated onUpdate and disposed on remove`() {
7389
val child = TestView()

0 commit comments

Comments
 (0)