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

JPanel渲染异常:超出JFrame范围,元素绘制位置错误

AWT/Swing组件渲染位置异常问题:元素出现在窗口底部边框外侧

在AWT/Swing中,当指定小于窗口高度的y坐标绘制组件时,元素并未渲染到预期位置,反而出现在窗口底部边框的外侧。以下是复现代码及测试场景:

public class Main {
    public static GameWindow window;
    public static void main(String[] args) {
        window = new GameWindow();
    }
}

class GameWindow extends JFrame {
    private final GamePanel panel;
    public GameWindow() {
        super();
        this.setSize(600, 400); //注意此处高度为400
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        panel = new GamePanel();
        this.add(panel);
        //取消注释下方代码,观察方块是否渲染到正确位置
        //setUndecorated(true);
        this.setVisible(true);
    }
    //取消注释下方方法,查看底部边框上方的黑线
    /*@Override
    public int getHeight() {
        return panel.getHeight();
    }*/
}

class GamePanel extends JPanel {
    public GamePanel() {
        super();
    }
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        //此处应渲染在底部边框上方,但实际渲染在外侧
        g.fill3DRect(0, Main.window.getHeight() - 22, 22, 22, false);
    }
}

测试场景

  • 场景1:保留窗口装饰时,需调整窗口大小才能看到方块。
  • 场景2:设置JFrame为无装饰状态时,方块渲染在预期的底部边框上方。
  • 场景3:保留窗口装饰但重写getHeight方法返回面板高度时,窗口底部会出现一条黑线。

场景效果

场景1

场景1

场景2

场景2

场景3

场景3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 19:15:23