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

如何为JPanel设置圆角边框?用paintComponent还是内置方法?

给JPanel加圆角边框的两种方法

不用非得重写paintComponent,看你要哪种效果:

1. 只想要圆角边框线(背景还是直角)

你代码里已经用到现成方法了:new LineBorder(Color.RED, 5, true),第三个参数true就是让边框变成圆角的。但要注意,如果面板背景色和父容器不一样,直角的背景会从圆角边框的缝隙露出来,所以这种方法只适合面板背景和父容器相同的场景。

2. 要面板连背景一起是圆角(完全贴合边框)

这种情况就得重写paintComponent,配合圆角边框使用,保证背景也被切成圆角。给你个示例代码:

public class RoundedPanel extends JPanel {
    private int cornerRadius;

    public RoundedPanel(int radius) {
        super();
        this.cornerRadius = radius;
        // 设置圆角边框
        this.setBorder(BorderFactory.createLineBorder(Color.RED, 5, true));
        // 关闭不透明,避免默认的矩形背景绘制
        this.setOpaque(false);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();
        // 开启抗锯齿,让圆角更顺滑
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // 绘制圆角背景
        g2d.setColor(getBackground());
        g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, cornerRadius, cornerRadius);
        g2d.dispose();
    }
}

然后在你的gameboard方法里替换原来的JPanel:

JPanel squarePane = new RoundedPanel(20); // 20是圆角半径,可按需调整大小
squarePane.setBackground(Color.BLUE);
squarePane.setPreferredSize(new Dimension(850, 700));
squarePane.setLayout(new GridBagLayout());

这样就能实现你要的那种边框和背景完全贴合的圆角效果了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 10:05:19