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

Java Swing自定义JButton边框:多边形样式按钮实现求助

自定义多边形样式JButton实现代码

我正在尝试创建一款特定样式的自定义JButton,通过继承JButton并重写相关方法来实现,以下是目前的代码:

class PolygonButton extends JButton {
    public PolygonButton(String value) {
        super(value);
    }
    
    Polygon polygon;

    @Override
    public boolean contains(int x, int y) {
        int width = getSize().width;
        int height = getSize().height;
        int xPoints[] = { width / 5, width, width, width - width / 5, 0, 0, width / 5 };
        int yPoints[] = { 0, 0, height - height / 5, height, height, height / 5, ... };
        // 这里需要补全yPoints数组的剩余元素,后续可初始化polygon对象实现精准点击判断
        // 示例:polygon = new Polygon(xPoints, yPoints, xPoints.length);
        // return polygon.contains(x, y);
        return super.contains(x, y);
    }
}

实现要点提示:

  • 重写contains方法是为了让按钮的有效点击范围和多边形外观匹配,替代默认的矩形点击判断
  • 必须补全yPoints数组的剩余元素,保证顶点数量和xPoints一致,否则无法生成合法的多边形
  • 最终建议用polygon.contains(x, y)替代super.contains(x, y),这样点击区域才会和自定义多边形完全贴合

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:32:52