透明的JButton仍在绘制其背景

4

我有一个半透明的JPanel。我通过扩展JButton创建了一个自定义按钮,因为我需要一个带有圆角的按钮,并想要添加一些效果。我将按钮设置为非不透明。当我将此按钮添加到我的半透明JPanel中时,它看起来很好。但是,在鼠标悬停时,按钮后面会绘制一个黑色补丁,看起来真的很糟糕。我在网上搜索了解决方案,但没有找到有用的解决方案。这个问题也在http://www.java.net/node/661798中描述,但我无法真正使kirillcool的建议奏效.....任何帮助将不胜感激。


1
不是针对你的问题的答案,但你尝试过下载/使用另一个外观而不是编写自己的吗?我在上一个项目中使用了Synthetica,它非常好看和“花哨”。 - Kaj
2个回答

7
我认为你需要添加:

我相信你需要添加:

button.setContentAreaFilled( false );

0

不确定是否还有人感兴趣... 您可以通过覆盖paintComponent()方法来解决问题,让Java以任何您喜欢的形状绘制JButton。您只需要使用setBackground()方法将Graphics对象的背景设置为透明。此外,在使用clearRect()方法清除Graphics对象之前,您需要清除Graphics对象,然后再用您的JButton背景的alpha级别填充它。这是我的一段代码...它显示了重写的paintComponent()。将其粘贴到您的JButton中,即可获得具有圆角边缘的JButton,即使它在半透明背景上也是如此。

private int outerRoundRectSize = 10;
private int innerRoundRectSize = 8;

public void paintComponent(Graphics g) 
{
    int h = getHeight();
    int w = getWidth();

    Graphics2D g2d = (Graphics2D) g.create();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);

    Color GP = null;

    //////////////get rid of the black background////////////////////////
    g2d.setBackground(new Color(0,0,0,0.0f));
    g2d.clearRect(0, 0, w, h);
    g2d.setPaint(new Color(0,0,0,0.3f));
    g2d.fillRect(0, 0, w, h);
    //////////////get rid of the black background////////////////////////

    ButtonModel model = getModel();
    if(!model.isEnabled()) 
    {
        setForeground(Color.GRAY);
        GP = new Color(0.5f,0.2f,0.6f);
    }
    else
    {
        setForeground(Color.WHITE);
        if(model.isRollover()) 
        {
            GP = new Color(0.5f,0.2f,0.6f);
        } 
        else 
        {
            GP = new Color(0.0f,1.0f,0.0f);
        }   
    }
    g2d.setPaint(GP);
    Color p1 = null;
    Color p2 = null;

    if(getModel().isPressed()) 
    {
        GP = new Color(1.0f,0.0f,0.0f);
        g2d.setPaint(GP);
        p1=new Color(0.12f,0.7f,0.3f);
        p2=new Color(0.7f,0.5f,0.6f);
    } 
    else 
    {
        p1=new Color(0.0f,0.5f,0.7f);
        p2=new Color(0.0f,1.0f,1.0f);
        GP = new Color(0.0f,0.0f,1.0f);
    }

    RoundRectangle2D.Float r2d = new RoundRectangle2D.Float(0, 0, w - 1, h - 1, outerRoundRectSize, outerRoundRectSize);
    Shape clip = g2d.getClip();
    g2d.clip(r2d);
    //g2d.fillRect(0, 0, w, h);
    g2d.fillRoundRect(0, 0, w, h, outerRoundRectSize, outerRoundRectSize);
    g2d.setClip(clip);
    g2d.setPaint(p1);
    g2d.drawRoundRect(0, 0, w - 1, h - 1, outerRoundRectSize,outerRoundRectSize);
    g2d.setPaint(p2);
    g2d.drawRoundRect(1, 1, w - 3, h - 3, innerRoundRectSize,innerRoundRectSize);

    g2d.dispose();
    super.paintComponent(g);
}

不要在配置单个属性时编写自定义代码,这样就可以轻松解决问题了 :-) 顺便说一下,请学习Java命名约定并遵循它们。 - kleopatra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接