java - 使用 Java 的圆形 Swing JButton

标签 java swing jbutton

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

持有这个按钮的 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/

相关文章:

java - Java 中文本字段中的首字母大写

java - 如何在java中为jbutton添加快捷键?

java - JButton 中的图像自动调整?

java - 如何使用泛型在抽象类中注入(inject)服务

java - mp3 文件格式

java - 通过 ActionListener 重绘未执行

Java isRollover() 方法在我的 swing 应用程序中不产生事件

Java NullPointerException 即使变量有一个值

java - Java 中的优先级队列

java - ProcessBuilder 在包含本地环境变量的命令上失败