blob: 15f099adcacf2c2944bf5e317a85a4108041b1e5 [file] [log] [blame]
Roman Elizarovf16fd272017-02-07 11:26:00 +03001/*
2 * Copyright 2016-2017 JetBrains s.r.o.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Roman Elizarovfbb36d32017-01-23 16:03:54 +030017package examples
18
Roman Elizarov3754f952017-01-18 20:47:54 +030019import kotlinx.coroutines.experimental.future.await
20import kotlinx.coroutines.experimental.launch
21import kotlinx.coroutines.experimental.swing.Swing
Denis Zharkov8e4e0e42016-06-22 18:27:19 +030022import java.awt.Insets
23import java.util.concurrent.CompletableFuture
24import javax.swing.*
25
26private fun createAndShowGUI() {
27 val frame = JFrame("Async UI example")
28 frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
29
30 val jProgressBar = JProgressBar(0, 100).apply {
31 value = 0
32 isStringPainted = true
33 }
34
35 val jTextArea = JTextArea(11, 10)
36 jTextArea.margin = Insets(5, 5, 5, 5)
37 jTextArea.isEditable = false
38
39 val panel = JPanel()
40
41 panel.add(jProgressBar)
42 panel.add(jTextArea)
43
44 frame.contentPane.add(panel)
45 frame.pack()
46 frame.isVisible = true
47
Roman Elizarov3754f952017-01-18 20:47:54 +030048 launch(Swing) {
Denis Zharkov8e4e0e42016-06-22 18:27:19 +030049 for (i in 1..10) {
50 // 'append' method and consequent 'jProgressBar.setValue' are called
51 // within Swing event dispatch thread
52 jTextArea.append(
Denis Zharkovb4833122016-12-15 11:49:03 +030053 startLongAsyncOperation(i).await()
Denis Zharkov8e4e0e42016-06-22 18:27:19 +030054 )
55 jProgressBar.value = i * 10
56 }
57 }
58}
59
Denis Zharkov64970a42016-06-22 19:25:22 +030060private fun startLongAsyncOperation(v: Int) =
61 CompletableFuture.supplyAsync {
62 Thread.sleep(1000)
63 "Message: $v\n"
64 }
Denis Zharkov8e4e0e42016-06-22 18:27:19 +030065
66fun main(args: Array<String>) {
67 SwingUtilities.invokeLater(::createAndShowGUI)
68}