1. package C10.src.book.graphic;  
  2.  
  3. import java.awt.Color;  
  4. import java.awt.Dimension;  
  5. import java.awt.FlowLayout;  
  6. import java.awt.Graphics;  
  7. import java.awt.Shape;  
  8. import java.awt.geom.Ellipse2D;  
  9.  
  10. import javax.swing.JButton;  
  11. import javax.swing.JFrame;  
  12. import javax.swing.JLabel;  
  13.  
  14. /**  
  15.  * 制作一个圆形的按钮时,需要做两件事: 第一件事是重载一个适当的绘画方法以画出一个圆形。  
  16.  * 第二件事是设置一些事件使得只有当你点击圆形按钮的范围中的时侯按钮才会作出响应  
  17.  */ 
  18. public class CircleButton extends JButton {  
  19.  
  20.     public CircleButton(String label) {  
  21.         super(label);  
  22.  
  23.         // 获取按钮的最佳大小  
  24.         Dimension size = getPreferredSize();  
  25.         size.width = size.height = Math.max(size.width, size.height);  
  26.         setPreferredSize(size);  
  27.  
  28.         setContentAreaFilled(false);  
  29.     }  
  30.  
  31.     // 画圆的按钮的背景和标签  
  32.     protected void paintComponent(Graphics g) {  
  33.  
  34.         if (getModel().isArmed()) {  
  35.             g.setColor(Color.lightGray); // 点击时高亮  
  36.         } else {  
  37.             g.setColor(getBackground());  
  38.         }  
  39.         // fillOval方法画一个矩形的内切椭圆,并且填充这个椭圆,  
  40.         // 当矩形为正方形时,画出的椭圆便是圆  
  41.         g.fillOval(00, getSize().width - 1, getSize().height - 1);  
  42.  
  43.         super.paintComponent(g);  
  44.     }  
  45.  
  46.     // 用简单的弧画按钮的边界。  
  47.     protected void paintBorder(Graphics g) {  
  48.         g.setColor(Color.white);  
  49.         // drawOval方法画矩形的内切椭圆,但不填充。只画出一个边界  
  50.         g.drawOval(00, getSize().width - 1, getSize().height - 1);  
  51.     }  
  52.  
  53.     // shape对象用于保存按钮的形状,有助于侦听点击按钮事件  
  54.     Shape shape;  
  55.  
  56.     public boolean contains(int x, int y) {  
  57.  
  58.         if ((shape == null) || (!shape.getBounds().equals(getBounds()))) {  
  59.             // 构造一个椭圆形对象  
  60.             shape = new Ellipse2D.Float(00, getWidth(), getHeight());  
  61.         }  
  62.         // 判断鼠标的x、y坐标是否落在按钮形状内。  
  63.         return shape.contains(x, y);  
  64.     }  
  65.  
  66.     public static void main(String[] args) {  
  67.         JButton button = new CircleButton("");  
  68.         button.setBackground(Color.orange);  
  69.  
  70.         JFrame frame = new JFrame("圆形按钮");  
  71.         frame.getContentPane().setBackground(Color.pink);  
  72.         frame.getContentPane().setLayout(new FlowLayout());  
  73.         frame.getContentPane().add(button);  
  74.         frame.setSize(200200);  
  75.         frame.setVisible(true);  
  76.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  77.     }  
  78.