使用 Java 的圆形 Swing JButton

新手上路,请多包涵

好吧,我有一张图片,我想将其作为按钮(或可点击的东西)的背景。问题是这张图片是圆形的,所以我需要显示这张图片,没有任何边框等。

容纳此按钮的 JComponent 具有自定义背景,因此按钮实际上只需要显示图像。

谷歌搜索后,我无法做到这一点。我尝试了以下所有方法,但没有运气:

 button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.setOpaque(true);

在我在背景上绘制图标后,按钮绘制它,但有一个带有边框的丑陋灰色背景等。我还尝试使用 JLabel 和 JButton。并在其上绘制一个 ImageIcon,但如果用户调整窗口大小或最小化窗口,图标就会消失!

我怎样才能解决这个问题?

我只需要将图像绘制并舍入到 JComponent 并听取点击…

原文由 José Leal 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 907
1 个回答

创建一个新的 Jbutton:

     JButton addBtn = new JButton("+");
    addBtn.setBounds(x_pos, y_pos, 30, 25);
    addBtn.setBorder(new RoundedBorder(10)); //10 is the radius
    addBtn.setForeground(Color.BLUE);

在为 JButton 设置边框时,调用覆盖的 javax.swing.border.Border 类。

 addBtn.setBorder(new RoundedBorder(10));

这是班级

private static class RoundedBorder implements Border {

    private int radius;

    RoundedBorder(int radius) {
        this.radius = radius;
    }

    public Insets getBorderInsets(Component c) {
        return new Insets(this.radius+1, this.radius+1, this.radius+2, this.radius);
    }

    public boolean isBorderOpaque() {
        return true;
    }

    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
        g.drawRoundRect(x, y, width-1, height-1, radius, radius);
    }
}

原文由 Lalchand 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题