import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Shape;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.RoundRectangle2D;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MyButton extends JButton implements MouseListener {
private Shape shape = null;
private Color click = new Color(0, 0, 113);// 按下時的顏色
private Color quit = new Color(237, 234, 228);// 離開時顏色
public MyButton(String s) {
super(s);
addMouseListener(this);
setContentAreaFilled(false);// 是否顯示外圍矩形地區 選否
}
public MyButton() {
super();
addMouseListener(this);
}
public MyButton(String text, Icon icon) {
super(text, icon);
addMouseListener(this);
}
public MyButton(Icon icon) {
super(icon);
addMouseListener(this);
}
public void setColor(Color c, Color q) {
click = c;
quit = q;
}
public void mouseClicked(MouseEvent e) {
System.out.println("mouseClicked");
}
public void mousePressed(MouseEvent e) {
System.out.println("mousePressed");
}
public void mouseReleased(MouseEvent e) {
System.out.println("mouseReleased");
}
public void mouseExited(MouseEvent e) {
System.out.println("mouseExited");
}
public void mouseEntered(MouseEvent e) {
System.out.println("mouseEntered");
}
public void paintComponent(Graphics g) {
//如果按下則為CLICK色 否則為 QUIT色
if (getModel().isArmed()) {
g.setColor(click);
} else {
g.setColor(quit);
}
//填充圓角矩形地區 也可以為其它的圖形
g
.fillRoundRect(0, 0, getSize().width - 1, getSize().height - 1,
20, 20);
//必須放在最後 否則畫不出來
super.paintComponent(g);
}
public void paintBorder(Graphics g) {
//畫邊界地區
g.setColor(click);
g
.drawRoundRect(0, 0, getSize().width - 1, getSize().height - 1,
20, 20);
}
public boolean contains(int x, int y) {
//判斷點(x,y)是否在按鈕內
if (shape == null || !(shape.getBounds().equals(getBounds()))) {
shape = new RoundRectangle2D.Float(0, 0, getWidth(), getHeight(),
20, 20);
}
return shape.contains(x, y);
}
public static void main(String[] argv) {
JFrame f = new JFrame();
f.setSize(400, 300);
MyButton btn = new MyButton("button");
f.getContentPane().add(btn, BorderLayout.NORTH);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}