kotlin完全兼容java,而且表达能力比java强很多,我今天尝试了使用kotlin编写java swing ,可以使用kotlin将其包装为声明式UI,这将大大改善原生java swing的使用体验.
将GridBagConstraint改造为GBC,可以链式调用,详细内容见https://editor.csdn.net/md/?articleId=108300061 接着对原来的JFrame,JButton做一些扩展函数
import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.LayoutManager
import java.awt.event.ActionEvent
import javax.swing.*
typealias AddComponent = JPanel.() -> Unit;
public fun App(
title: String,
size: Dimension = Dimension(400, 400),
layout: LayoutManager = BorderLayout(),
panel: JFrame.() -> Unit
) {
SwingUtilities.invokeLater {
val frame = JFrame(title);
frame.size = size;
frame.layout = layout;
panel(frame)
frame.isVisible = true;
frame.defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE;
}
}
public fun JFrame.Panel(layout: LayoutManager = BorderLayout(), modifier: Any? = null, content: AddComponent) {
val jPanel = JPanel()
jPanel.layout = layout;
content(jPanel)
if (modifier != null)
this.add(jPanel, modifier)
else
this.add(jPanel)
}
public fun JComponent.Panel(layout: LayoutManager = BorderLayout(), modifier: Any? = null, content: AddComponent) {
this.layout = layout;
val jPanel = JPanel()
content(jPanel)
addComponent(jPanel, modifier)
}
private fun JComponent.addComponent(component: JComponent, modifier: Any? = null) {
if (modifier != null)
this.add(component, modifier)
else
this.add(component)
}
public fun JComponent.Label(title: String, modifier: Any?): JLabel {
val label = JLabel(title)
this.addComponent(label, modifier)
return label
}
fun JButton.onClick(eventListener: (event: ActionEvent) -> Unit): JButton {
this.addActionListener {
eventListener(it);
};
return this;
}
public fun JComponent.Button(title: String, modifier: Any?): JButton {
val button = JButton(title)
this.addComponent(button, modifier)
return button
}
在main函数中调用,就有一种声明式UI的感觉
import java.awt.GridBagLayout
fun main() {
App("测试一下") {
Panel(GridBagLayout()) {
Label("哈哈哈哈哈哈", GBC(0, 0).setWeight(1, 1))
Label("呵呵呵呵呵呵", GBC(0, 1).setWeight(1, 2))
Button("点击打印", GBC(1, 0, 1, 2).setWeight(1, 1))
.onClick { println("按钮的ID为${it.id}") }
}
}
}
kotlin真是一门相当优秀的现代编程语言
|