4

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

4

2 回答 2

7

我相信您需要添加:

button.setContentAreaFilled( false );
于 2011-05-08T17:10:29.927 回答
0

不确定是否有人仍然感兴趣...您可以通过覆盖该paintComponent()方法来解决问题,让 Java 以JButton您喜欢的任何形状绘制。您只需要使用setBackground()方法将 Graphics 对象的背景设置为透明即可。clearRect()您还需要在使用方法在其上绘制之前清除 Graphics 对象,然后使用JButton. 这是我的一段代码..它显示了覆盖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);
}
于 2012-03-04T18:50:20.677 回答