-
Notifications
You must be signed in to change notification settings - Fork 5
/
App.kt
252 lines (223 loc) · 6.52 KB
/
App.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
package example
import java.awt.*
import java.awt.event.HierarchyEvent
import java.util.TreeSet
import java.util.concurrent.Executors
import javax.swing.*
import javax.swing.table.DefaultTableCellRenderer
import javax.swing.table.DefaultTableModel
import javax.swing.table.TableModel
import javax.swing.table.TableRowSorter
private val model = WorkerModel()
private val table = JTable(model)
private val sorter = TableRowSorter(model)
private val deleteRowSet = TreeSet<Int>()
private val executor = Executors.newSingleThreadExecutor()
fun makeUI(): Component {
table.rowSorter = sorter
model.addProgressValue("Name 1", 100, null)
val scrollPane = JScrollPane(table)
scrollPane.viewport.background = Color.WHITE
table.componentPopupMenu = TablePopupMenu()
table.fillsViewportHeight = true
table.intercellSpacing = Dimension()
table.setShowGrid(false)
table.putClientProperty("terminateEditOnFocusLost", true)
table.columnModel.getColumn(0).also {
it.maxWidth = 60
it.minWidth = 60
it.resizable = false
}
table.columnModel.getColumn(2).cellRenderer = ProgressRenderer()
return JPanel(BorderLayout()).also {
it.addHierarchyListener { e ->
val cf = e.changeFlags.toInt() and HierarchyEvent.DISPLAYABILITY_CHANGED
if (cf != 0 && !e.component.isDisplayable) {
executor.shutdownNow()
}
}
val button = JButton("add")
button.addActionListener { addActionPerformed() }
it.add(button, BorderLayout.SOUTH)
it.add(scrollPane)
it.preferredSize = Dimension(320, 240)
}
}
private fun addActionPerformed() {
val key = model.rowCount
val worker = object : BackgroundTask() {
override fun process(c: List<Int>) {
if (table.isDisplayable && !isCancelled) {
c.forEach { model.setValueAt(it, key, 2) }
} else {
cancel(true)
executor.shutdown()
}
}
override fun done() {
var i = -1
val message = runCatching {
i = get()
if (i >= 0) "Done" else "Disposed"
}.getOrNull() ?: "Interrupted"
model.setValueAt("$message(${i}ms)", key, 2)
// executor.remove(this)
}
}
model.addProgressValue("example", 0, worker)
executor.execute(worker)
}
private fun cancelActionPerformed() {
for (i in table.selectedRows) {
val mi = table.convertRowIndexToModel(i)
model.getSwingWorker(mi)?.takeUnless { it.isDone }?.cancel(true)
}
table.repaint()
}
private fun deleteActionPerformed() {
val selection = table.selectedRows
if (selection.isEmpty()) {
return
}
for (i in selection) {
val mi = table.convertRowIndexToModel(i)
deleteRowSet.add(mi)
model.getSwingWorker(mi)?.takeUnless { it.isDone }?.cancel(true)
}
sorter.rowFilter = object : RowFilter<TableModel, Int>() {
override fun include(entry: Entry<out TableModel, out Int>) =
!deleteRowSet.contains(entry.identifier)
}
table.clearSelection()
table.repaint()
}
private class TablePopupMenu : JPopupMenu() {
private val cancelMenuItem: JMenuItem
private val deleteMenuItem: JMenuItem
init {
add("add").addActionListener { addActionPerformed() }
addSeparator()
cancelMenuItem = add("cancel")
cancelMenuItem.addActionListener { cancelActionPerformed() }
deleteMenuItem = add("delete")
deleteMenuItem.addActionListener { deleteActionPerformed() }
}
override fun show(
c: Component?,
x: Int,
y: Int,
) {
if (c is JTable) {
val flag = c.selectedRowCount > 0
cancelMenuItem.isEnabled = flag
deleteMenuItem.isEnabled = flag
super.show(c, x, y)
}
}
}
private open class BackgroundTask : SwingWorker<Int, Int>() {
private val randomSleep = (1..50).random()
@Throws(InterruptedException::class)
override fun doInBackground(): Int {
val lengthOfTask = 120
var current = 0
while (current <= lengthOfTask && !isCancelled) {
publish(100 * current / lengthOfTask)
Thread.sleep(randomSleep.toLong())
current++
}
return randomSleep * lengthOfTask
}
}
private open class WorkerModel : DefaultTableModel() {
private val workerMap = mutableMapOf<Int, SwingWorker<Int, Int>>()
private var number = 0
fun addProgressValue(
name: String,
iv: Int,
worker: SwingWorker<Int, Int>?,
) {
super.addRow(arrayOf(number, name, iv))
worker?.also { workerMap[number] = it }
number++
}
fun getSwingWorker(identifier: Int): SwingWorker<Int, Int>? {
val key = getValueAt(identifier, 0) as? Int ?: -1
return workerMap[key]
}
override fun isCellEditable(
row: Int,
col: Int,
) = COLUMN_ARRAY[col].isEditable
override fun getColumnClass(column: Int) = COLUMN_ARRAY[column].columnClass
override fun getColumnCount() = COLUMN_ARRAY.size
override fun getColumnName(column: Int) = COLUMN_ARRAY[column].columnName
private data class ColumnContext(
val columnName: String,
val columnClass: Class<*>,
val isEditable: Boolean,
)
companion object {
private val COLUMN_ARRAY = arrayOf(
ColumnContext("No.", Number::class.java, false),
ColumnContext("Name", String::class.java, false),
ColumnContext("Progress", Number::class.java, false),
)
}
}
private class ProgressRenderer : DefaultTableCellRenderer() {
private val progress = JProgressBar()
private val renderer: JPanel? = JPanel(BorderLayout())
override fun getTableCellRendererComponent(
table: JTable,
value: Any?,
isSelected: Boolean,
hasFocus: Boolean,
row: Int,
column: Int,
): Component {
var text = value
if (value is Int) {
text = "Done(0ms)"
if (value < 0) {
text = "Canceled"
} else if (value < progress.maximum && renderer != null) { // < 100
progress.value = value
renderer.add(progress)
renderer.isOpaque = false
renderer.border = BorderFactory.createEmptyBorder(2, 2, 2, 2)
return renderer
}
}
return super.getTableCellRendererComponent(
table,
text,
isSelected,
hasFocus,
row,
column,
)
}
override fun updateUI() {
super.updateUI()
isOpaque = false
renderer?.also { SwingUtilities.updateComponentTreeUI(it) }
}
}
fun main() {
EventQueue.invokeLater {
runCatching {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
}.onFailure {
it.printStackTrace()
Toolkit.getDefaultToolkit().beep()
}
JFrame().apply {
defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
contentPane.add(makeUI())
pack()
setLocationRelativeTo(null)
isVisible = true
}
}
}