gpt4 book ai didi

java - 使用 Java 的圆形 Swing JButton

转载 作者:太空狗 更新时间:2023-10-29 22:44:12 25 4
gpt4 key购买 nike

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

持有这个按钮的 JComponent 有一个自定义背景,所以按钮真的只需要显示图像。

在谷歌搜索后,我无法做到这一点。我已经尝试了以下所有方法,但没有成功:

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

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

我该如何解决这个问题?

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

最佳答案

创建一个新的 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);
}
}

关于java - 使用 Java 的圆形 Swing JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/423950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com