• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download

<lambda>null1 // This file was automatically generated from coroutines-guide-ui.md by Knit tool. Do not edit.
2 package kotlinx.coroutines.javafx.guide.exampleUiBlocking01
3 
4 import kotlinx.coroutines.*
5 import kotlinx.coroutines.channels.*
6 import kotlinx.coroutines.javafx.JavaFx as Main
7 import javafx.application.Application
8 import javafx.event.EventHandler
9 import javafx.geometry.*
10 import javafx.scene.*
11 import javafx.scene.input.MouseEvent
12 import javafx.scene.layout.StackPane
13 import javafx.scene.paint.Color
14 import javafx.scene.shape.Circle
15 import javafx.scene.text.Text
16 import javafx.stage.Stage
17 
18 fun main(args: Array<String>) {
19     Application.launch(ExampleApp::class.java, *args)
20 }
21 
22 class ExampleApp : Application() {
<lambda>null23     val hello = Text("Hello World!").apply {
24         fill = Color.valueOf("#C0C0C0")
25     }
26 
27     val fab = Circle(20.0, Color.valueOf("#FF4081"))
28 
<lambda>null29     val root = StackPane().apply {
30         children += hello
31         children += fab
32         StackPane.setAlignment(hello, Pos.CENTER)
33         StackPane.setAlignment(fab, Pos.BOTTOM_RIGHT)
34         StackPane.setMargin(fab, Insets(15.0))
35     }
36 
<lambda>null37     val scene = Scene(root, 240.0, 380.0).apply {
38         fill = Color.valueOf("#303030")
39     }
40 
startnull41     override fun start(stage: Stage) {
42         stage.title = "Example"
43         stage.scene = scene
44         stage.show()
45         setup(hello, fab)
46     }
47 }
48 
onClicknull49 fun Node.onClick(action: suspend (MouseEvent) -> Unit) {
50     val eventActor = GlobalScope.actor<MouseEvent>(Dispatchers.Main, capacity = Channel.CONFLATED) {
51         for (event in channel) action(event) // pass event to action
52     }
53     onMouseClicked = EventHandler { event ->
54         eventActor.trySend(event)
55     }
56 }
57 
fibnull58 fun fib(x: Int): Int =
59     if (x <= 1) x else fib(x - 1) + fib(x - 2)
60 
61 fun setup(hello: Text, fab: Circle) {
62     var result = "none" // the last result
63     // counting animation
64     GlobalScope.launch(Dispatchers.Main) {
65         var counter = 0
66         while (true) {
67             hello.text = "${++counter}: $result"
68             delay(100) // update the text every 100ms
69         }
70     }
71     // compute the next fibonacci number of each click
72     var x = 1
73     fab.onClick {
74         result = "fib($x) = ${fib(x)}"
75         x++
76     }
77 }
78