-
Notifications
You must be signed in to change notification settings - Fork 5
/
App.kt
102 lines (89 loc) · 2.21 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
package example
import java.awt.*
import java.awt.event.HierarchyEvent
import java.io.Serializable
import javax.swing.*
private val panelDim = Dimension(320, 240)
private val racket = Racket(panelDim)
private val absolute = JLabel("absolute:")
private val relative = JLabel("relative:")
fun makeUI(): Component {
val p = object : JPanel(BorderLayout()) {
override fun getPreferredSize() = panelDim
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
racket.draw(g)
}
}
val timer = Timer(10) {
val pi = MouseInfo.getPointerInfo()
val pt = pi.location
absolute.text = "absolute:$pt"
SwingUtilities.convertPointFromScreen(pt, p)
relative.text = "relative:$pt"
racket.move(pt.x)
p.repaint()
}
p.addHierarchyListener { e ->
if (e.changeFlags and HierarchyEvent.DISPLAYABILITY_CHANGED.toLong() != 0L) {
if (e.component.isDisplayable) {
timer.start()
} else {
timer.stop()
}
}
}
val box = Box.createVerticalBox()
box.add(absolute)
box.add(relative)
box.border = BorderFactory.createEmptyBorder(5, 5, 5, 5)
p.add(box)
return p
}
private class Racket(
private val parentSize: Dimension,
) : Serializable {
private var centerPos: Int
init {
centerPos = parentSize.width / 2
}
fun draw(g: Graphics) {
g.color = Color.RED
g.fillRect(
centerPos - WIDTH / 2,
parentSize.height - HEIGHT,
WIDTH,
HEIGHT,
)
}
fun move(pos: Int) {
centerPos = pos
if (centerPos < WIDTH / 2) {
centerPos = WIDTH / 2
} else if (centerPos > parentSize.width - WIDTH / 2) {
centerPos = parentSize.width - WIDTH / 2
}
}
companion object {
private const val serialVersionUID = 1L
private const val WIDTH = 80
private const val HEIGHT = 5
}
}
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
}
}
}