-
Notifications
You must be signed in to change notification settings - Fork 5
/
App.kt
74 lines (68 loc) · 1.76 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
package example
import java.awt.*
import javax.swing.*
import javax.swing.text.DefaultEditorKit
import javax.swing.text.JTextComponent
fun makeUI(): Component {
val txt = """
ComponentPopupMenu Test
111111111111
22222222
33333333
""".trimIndent()
val textArea = JTextArea(txt)
textArea.componentPopupMenu = TextComponentPopupMenu()
return JPanel(BorderLayout()).also {
it.add(JScrollPane(textArea))
it.preferredSize = Dimension(320, 240)
}
}
private class TextComponentPopupMenu : JPopupMenu() {
private val cutAction = DefaultEditorKit.CutAction()
private val copyAction = DefaultEditorKit.CopyAction()
private val deleteItem: JMenuItem
init {
add(cutAction)
add(copyAction)
add(DefaultEditorKit.PasteAction())
addSeparator()
deleteItem = add("delete")
deleteItem.addActionListener {
(invoker as? JTextComponent)?.replaceSelection(null)
}
addSeparator()
add(DefaultEditorKit.selectAllAction).addActionListener {
(invoker as? JTextComponent)?.selectAll()
}
}
override fun show(
c: Component?,
x: Int,
y: Int,
) {
if (c is JTextComponent) {
val hasSelectedText = c.selectedText != null
cutAction.isEnabled = hasSelectedText
copyAction.isEnabled = hasSelectedText
deleteItem.isEnabled = hasSelectedText
super.show(c, x, y)
}
}
}
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
}
}
}