我有一个半透明 JPanel。我通过扩展JButton创建了一个自定义JButton ,因为我需要一个带圆角的按钮,并希望为它添加一些效果。我已将按钮设为非不透明。当我将这个按钮添加到我的半透明JPanel时,它很好。但是在翻滚时,按钮后面会画一个黑色的补丁,看起来很糟糕。我在网上寻找解决方案但却找不到有用的解决方案。这个问题也在http://www.java.net/node/661798描述,但我无法真正让kirillcool的建议工作.....任何帮助将不胜感激
答案 0 :(得分:7)
我相信你需要添加:
button.setContentAreaFilled( false );
答案 1 :(得分:0)
不确定某人是否还有兴趣...
您可以通过覆盖paintComponent()
方法来解决问题,让Java以您喜欢的任何形状绘制JButton
。您只需要使用setBackground()
方法将Graphics对象的背景设置为透明。您还需要在使用clearRect()
方法绘制图形对象之前清除它,然后使用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);
}