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