-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
example-ui-actor-03.kt
68 lines (59 loc) · 2.06 KB
/
example-ui-actor-03.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// This file was automatically generated from coroutines-guide-ui.md by Knit tool. Do not edit.
package kotlinx.coroutines.javafx.guide.exampleUiActor03
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.javafx.JavaFx as Main
import javafx.application.Application
import javafx.event.EventHandler
import javafx.geometry.*
import javafx.scene.*
import javafx.scene.input.MouseEvent
import javafx.scene.layout.StackPane
import javafx.scene.paint.Color
import javafx.scene.shape.Circle
import javafx.scene.text.Text
import javafx.stage.Stage
fun main(args: Array<String>) {
Application.launch(ExampleApp::class.java, *args)
}
class ExampleApp : Application() {
val hello = Text("Hello World!").apply {
fill = Color.valueOf("#C0C0C0")
}
val fab = Circle(20.0, Color.valueOf("#FF4081"))
val root = StackPane().apply {
children += hello
children += fab
StackPane.setAlignment(hello, Pos.CENTER)
StackPane.setAlignment(fab, Pos.BOTTOM_RIGHT)
StackPane.setMargin(fab, Insets(15.0))
}
val scene = Scene(root, 240.0, 380.0).apply {
fill = Color.valueOf("#303030")
}
override fun start(stage: Stage) {
stage.title = "Example"
stage.scene = scene
stage.show()
setup(hello, fab)
}
}
fun setup(hello: Text, fab: Circle) {
fab.onClick { // start coroutine when the circle is clicked
for (i in 10 downTo 1) { // countdown from 10 to 1
hello.text = "Countdown $i ..." // update text
delay(500) // wait half a second
}
hello.text = "Done!"
}
}
fun Node.onClick(action: suspend (MouseEvent) -> Unit) {
// launch one actor to handle all events on this node
val eventActor = GlobalScope.actor<MouseEvent>(Dispatchers.Main, capacity = Channel.CONFLATED) { // <--- Changed here
for (event in channel) action(event) // pass event to action
}
// install a listener to send events to this actor
onMouseClicked = EventHandler { event ->
eventActor.trySend(event)
}
}