1 /*
2  * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3  */
4 
5 package examples
6 
7 import kotlinx.coroutines.*
8 import kotlinx.coroutines.future.*
9 import kotlinx.coroutines.swing.*
10 import java.awt.*
11 import java.util.concurrent.*
12 import javax.swing.*
13 
createAndShowGUInull14 private fun createAndShowGUI() {
15     val frame = JFrame("Async UI example")
16     frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
17 
18     val jProgressBar = JProgressBar(0, 100).apply {
19         value = 0
20         isStringPainted = true
21     }
22 
23     val jTextArea = JTextArea(11, 10)
24     jTextArea.margin = Insets(5, 5, 5, 5)
25     jTextArea.isEditable = false
26 
27     val panel = JPanel()
28 
29     panel.add(jProgressBar)
30     panel.add(jTextArea)
31 
32     frame.contentPane.add(panel)
33     frame.pack()
34     frame.isVisible = true
35 
36     GlobalScope.launch(Dispatchers.Swing) {
37         for (i in 1..10) {
38             // 'append' method and consequent 'jProgressBar.setValue' are called
39             // within Swing event dispatch thread
40             jTextArea.append(
41                     startLongAsyncOperation(i).await()
42             )
43             jProgressBar.value = i * 10
44         }
45     }
46 }
47 
startLongAsyncOperationnull48 private fun startLongAsyncOperation(v: Int) =
49         CompletableFuture.supplyAsync {
50             Thread.sleep(1000)
51             "Message: $v\n"
52         }
53 
mainnull54 fun main(args: Array<String>) {
55     SwingUtilities.invokeLater(::createAndShowGUI)
56 }
57