You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows下Kotlin Swing中JTextField随机错位渲染问题求助

解决Windows下Swing JTextField点击自定义JComboBox后渲染错位问题

问题现象

使用Kotlin+Swing开发桌面应用时,登录表单中输入JTextField内容后点击自定义JComboBox,JTextField会错位渲染到组合框所在位置,该问题仅在Windows系统中出现。

聚焦前效果:
聚焦前的登录表单,JTextField位置正常

聚焦后效果:
点击JComboBox后,JTextField错位渲染到组合框位置

问题根源

你的SelectDistrictBoxUI类中,paint方法手动调用了g2.dispose(),这违反了Swing的渲染规范:Swing传递给组件的Graphics对象是共享上下文,手动释放会导致后续其他组件(比如JTextField)无法正常使用该上下文完成渲染,进而引发错位问题。

解决步骤

  1. 移除Graphics对象的手动释放:删除SelectDistrictBoxUI中paint方法里的g2.dispose()调用,由Swing自行管理Graphics资源。
  2. 规范自定义UI的paint方法逻辑:如果不需要自定义绘制UI逻辑,直接留空方法体即可,不要执行多余操作。
  3. 可选:完善组件背景绘制:如果自定义JComboBox需要背景,建议取消paintComponent中drawBackgroundBox(g2)的注释,确保组件不透明性设置和背景绘制逻辑一致,避免渲染残留。

修改后的代码示例

SelectDistrictBoxUI.kt

import java.awt.Graphics2D
import java.awt.Rectangle
import javax.swing.JButton
import javax.swing.JComponent
import javax.swing.plaf.basic.BasicComboBoxUI

class SelectDistrictBoxUI : BasicComboBoxUI() {

    override fun paint(g: Graphics?, c: JComponent?) {
        // 移除g2.dispose()调用,无需手动释放Graphics对象
    }

    override fun paintCurrentValueBackground(g: Graphics?, bounds: Rectangle?, hasFocus: Boolean) {
    }

    override fun paintCurrentValue(g: Graphics?, bounds: Rectangle?, hasFocus: Boolean) {
    }

    override fun createArrowButton(): JButton {
        val btn = JButton()
        btn.isVisible = false
        return btn
    }

    override fun createPopup() = SelectDistrictBoxPopup(comboBox)
}

可选:完善SelectDistrictBox的背景绘制

override fun paintComponent(g: Graphics?) {
    val g2 = g as Graphics2D
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON)

    // 恢复背景绘制,确保组件视觉完整性
    drawBackgroundBox(g2)

    drawSelectedItemLabel(g2)
    drawArrowIcon(g2)
}

内容的提问来源于stack exchange,提问作者ishaangupte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 06:41:00