I have a translucent JPanel. I have created a custom JButton by extending JButton as I required a button with rounded corners and wanted to add some effects to it. I have made the button non-opaque. When I add this button to my translucent JPanel it apears fi开发者_JAVA百科ne. But on rollover a black patch is painted behind the button which looks really crappy. I searched the net for a solution but could'nt find a useful one . This problem is also described at http://www.java.net/node/661798 but i was not able really make kirillcool's suggestion work out.....Any help will be appreciated
I believe you need to add:
button.setContentAreaFilled( false );
not sure if someone is still interested...
you can fix the problem by overriding the paintComponent()
method to let Java draw the JButton
in any Shape you like. you just need to set the background of the Graphics object to transparent with setBackground()
method. also you need to clear the Graphics object BEFORE drawing on it with clearRect()
method and then fill it again with the alpha level of the background of your JButton
. here is my piece of code.. it shows the overriden paintComponent()
. by pasting it into your JButton
you should get a JButton
with rounded edges even if its on semi-transparant background
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);
}
精彩评论