1 package examples
2
3 import javafx.application.Application
4 import javafx.scene.Scene
5 import javafx.scene.control.*
6 import javafx.scene.layout.GridPane
7 import javafx.stage.Stage
8 import javafx.beans.property.SimpleStringProperty
9 import javafx.event.EventHandler
10 import kotlinx.coroutines.*
11 import kotlinx.coroutines.flow.*
12 import kotlinx.coroutines.javafx.*
13 import kotlin.coroutines.CoroutineContext
14
mainnull15 fun main(args: Array<String>) {
16 Application.launch(FxAsFlowApp::class.java, *args)
17 }
18
19 /**
20 * Adapted from
21 * https://github.com/ReactiveX/RxJavaFX/blob/a78ca7d15f7d82d201df8fafb6eba732ec17e327/src/test/java/io/reactivex/rxjavafx/RxJavaFXTest.java
22 */
23 class FxAsFlowApp: Application(), CoroutineScope {
24
25 private var job = Job()
26 override val coroutineContext: CoroutineContext
27 get() = JavaFx + job
28
29 private val incrementButton = Button("Increment")
30 private val incrementLabel = Label("")
31 private val textInput = TextField()
32 private val flippedTextLabel = Label()
33 private val spinner = Spinner<Int>()
34 private val spinnerChangesLabel = Label()
35
startnull36 public override fun start( primaryStage: Stage) {
37 val gridPane = GridPane()
38 gridPane.apply {
39 hgap = 10.0
40 vgap = 10.0
41 add(incrementButton, 0, 0)
42 add(incrementLabel, 1, 0)
43 add(textInput, 0, 1)
44 add(flippedTextLabel, 1, 1)
45 add(spinner, 0, 2)
46 add(spinnerChangesLabel, 1, 2)
47 }
48 val scene = Scene(gridPane)
49 primaryStage.apply {
50 width = 275.0
51 setScene(scene)
52 show()
53 }
54 }
55
stopnull56 public override fun stop() {
57 super.stop()
58 job.cancel()
59 job = Job()
60 }
61
62 init {
63 // Initializing the "Increment" button
64 val stringProperty = SimpleStringProperty()
65 var i = 0
<lambda>null66 incrementButton.onAction = EventHandler {
67 i += 1
68 stringProperty.set(i.toString())
69 }
<lambda>null70 launch {
71 stringProperty.asFlow().collect {
72 if (it != null) {
73 stringProperty.set(it)
74 }
75 }
76 }
77 incrementLabel.textProperty().bind(stringProperty)
78 // Initializing the reversed text field
79 val stringProperty2 = SimpleStringProperty()
<lambda>null80 launch {
81 textInput.textProperty().asFlow().collect {
82 if (it != null) {
83 stringProperty2.set(it.reversed())
84 }
85 }
86 }
87 flippedTextLabel.textProperty().bind(stringProperty2)
88 // Initializing the spinner
89 spinner.valueFactory = SpinnerValueFactory.IntegerSpinnerValueFactory(0, 100)
90 spinner.isEditable = true
91 val stringProperty3 = SimpleStringProperty()
<lambda>null92 launch {
93 spinner.valueProperty().asFlow().collect {
94 if (it != null) {
95 stringProperty3.set("NEW: $it")
96 }
97 }
98 }
99 spinnerChangesLabel.textProperty().bind(stringProperty3)
100 }
101 }
102