关于美化JButton,先结合一个实例说吧。
package test;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import javax.swing.AbstractButton;
import javax.swing.JComponent;
import javax.swing.plaf.basic.BasicButtonUI;
public class MyButtonUI extends BasicButtonUI{
private static final Color BUTTON_COLOR1 = new Color(205,255,205);
private static final Color BUTTON_COLOR2 = new Color(51,154,47);
public MyButtonUI(){
super();
}
public void paint(Graphics g,JComponent c){
super.paint(g, c);
Graphics2D g2d=(Graphics2D)g;
int h=c.getHeight();
int w=c.getWidth();
float tran=1F;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
GradientPaint p1;
GradientPaint p2;
p1=new GradientPaint(0,0,new Color(0,0,0), 0,h-1,new Color(100,100,100));
p2=new GradientPaint(0,1,new Color(0,0,0,50),0,h-3,new Color(255,255,255,100));
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,tran));
RoundRectangle2D.Float r2d=new RoundRectangle2D.Float(0,0,w-1,h-1,20,20);
Shape clip=g2d.getClip();
g2d.clip(r2d);
GradientPaint gp=new GradientPaint(0.0F,0.0F,BUTTON_COLOR1,0.0F,h,BUTTON_COLOR2,true);
g2d.setPaint(gp);
g2d.fillRect(0,0,w,h);
g2d.setClip(clip);
g2d.setPaint(p1);
g2d.drawRoundRect(0,0,w-1,h-1,20,20);
g2d.setPaint(p2);
g2d.drawRoundRect(1,1,w-3,h-3,18,18);
}
}
这段代码的所显示的按钮如下图所示
但是很多时候绘制出来的按钮都有一个矩形的边框,那么如何去掉它呢?答案很简单,就是创建button的时候调用对象的setBorderPainted(false)以及setContentAreaFilled(false),setBorderPainter(false)设完了不就可以了,但为什么还要后面的setContentAreaFilled(false)呢?
这个是因为在重载BasicButtonUI的时候,重载方法intallUI()的时候往往需要设置Button的默认属性值,比如setBackground(),在设置ContentAreaFilled(false)后,这些属性值就都看不到了,所以我们看到的就是不同形状的按钮了。是不是很厉害?但是别忘了,此时的button还没有原来默认按钮按下就有边框的功能,此时我们重载BasicButtonUI的paintButtonPressed()方法,并微调一些数值,代码如下
@Override
protected void paintButtonPressed(Graphics g,AbstractButton b){
super.paintButtonPressed(g, b);
Graphics2D g2d=(Graphics2D)g;
int h=b.getHeight();
int w=b.getWidth();
float tran=1F;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
GradientPaint p1;
GradientPaint p2;
p1=new GradientPaint(0,0,new Color(0, 0, 0), 0,h-1,new Color(100,100,100));
p2=new GradientPaint(0,1,new Color(0,0,0,50),0,h-3,new Color(255,255,255,100));
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,tran));
RoundRectangle2D.Float r2d=new RoundRectangle2D.Float(0,0,w-1,h-1,20,20);
Shape clip=g2d.getClip();g2d.clip(r2d);
GradientPaint gp=new GradientPaint(0.0F,0.0F,BUTTON_COLOR1,0.0F,h,BUTTON_COLOR2,true);
g2d.setPaint(gp);
g2d.fillRect(0,0,w,h);
g2d.setClip(clip);
g2d.setPaint(p1);
g2d.drawRoundRect(0,0,w-2,h-2,20,20);
g2d.setPaint(p2);
g2d.drawRoundRect(1,1,w-4,h-4,18,18);
g2d.dispose();
}
这样按下按钮的时候就有反应了,具体效果如图。
通过自定义BasicButtonUI我们就可以绘制各种不同形状的按钮,自定义完成后不要忘记setUI()哦,这样才能看到你自定义的按钮的形状哦!!!