kotlin开发javaSwing(1.登录篇)
1)主页面:Login.kt
import main.component.BackgroundPanel import main.utils.PathUtils import org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper import java.io.File import javax.imageio.ImageIO import javax.swing.* /** * @Auther: Desker * @Date: 2022/1/18 14:44 * @Description: */ class Login(title: String) : JFrame(title) { init { try { BeautyEyeLNFHelper.launchBeautyEyeLNF(); // 隐藏右上角设置按钮 UIManager.put("RootPane.setupButtonVisible", false); // 将外观设置为系统外观. UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); createUi(title) } catch (e: Exception) { e.printStackTrace() } } private fun createUi(title: String) { val jframe = JFrame(title) // 窗体大小固定 jframe.isResizable = false jframe.defaultCloseOperation = EXIT_ON_CLOSE // 设置窗体图标 jframe.iconImage = ImageIO.read(File(PathUtils.getImagePath("os.png"))) // 背景面板 val read = ImageIO.read(File(PathUtils.getImagePath("login.jpg"))) val backgroundPanel = BackgroundPanel(read) // 用户名 val userBox = Box.createHorizontalBox() userBox.add(JLabel("用户名")) userBox.add(Box.createHorizontalStrut(20)) userBox.add(JTextField(20)) // 密码 val passBox = Box.createHorizontalBox() passBox.add(JLabel("密 码")) passBox.add(Box.createHorizontalStrut(20)) passBox.add(JTextField(20)) // 登录按钮 val butBox = Box.createHorizontalBox() val okBtn = JButton("登录") butBox.add(okBtn) butBox.add(Box.createHorizontalStrut(100)) val cancleBtn = JButton("取消") butBox.add(cancleBtn) val vbox = Box.createVerticalBox() vbox.add(Box.createVerticalStrut(100)) vbox.add(userBox) vbox.add(Box.createVerticalStrut(20)) vbox.add(passBox) vbox.add(Box.createVerticalStrut(30)) vbox.add(butBox) backgroundPanel.add(vbox) jframe.add(backgroundPanel) jframe.setSize(read.width, read.height) // 启动后就在屏幕正中央 jframe.setLocationRelativeTo(null); // 显示 jframe.isVisible = true } } fun main(args: Array<String>) { Login("登录") }
2)背景面板 BackgroundPanel.kt
import java.awt.Graphics import java.awt.Image import javax.swing.JPanel /** * @Auther: Desker * @Date: 2022/1/18 15:44 * @Description: */ class BackgroundPanel(backImage: Image) : JPanel() { var image = backImage override fun paintComponent(g: Graphics?) { super.paintComponent(g) if (g == null) return var x = 0 var y = 0 g.drawImage(image, x, y, this.height, this.width, this) while (true) { g.drawImage(image, x, y, this); if (x > this.width && y > this.height) break; //这段代码是为了保证在窗口大于图片时,图片仍能覆盖整个窗口 if (x > this.width) { x = 0; y += image.getHeight(null); } else x += image.getWidth(null); } } }
3)文件路径 PathUtils.kt
import java.nio.file.Paths /** * @Auther: Desker * @Date: 2022/1/18 16:18 * @Description: */ object PathUtils{ fun getImagePath(name:String): String { // 当前工作目录 val path = Paths.get("").toAbsolutePath().toString() return path+"\\src\\images\\"+ name } }
4)swingUI相关jar (beautyeye_inf.jar)
链接:https://pan.baidu.com/s/1RWorazrlKYYFSGw2u_uiQQ
提取码:olxz

浙公网安备 33010602011771号