int w = getSize().width;
int h = getSize().height;
int d = 50;
int r = d / 2;
g.fillArc(0,0,d,d,180,-90);
g.fillArc(w - d - 2, 0, d, d, 0, 90);
g.fillRect(r,0,w-d,r);
g.fillRect(0,r,w,h-r);
// This call will paint the label and the focus rectangle.
super.paintComponent(g);
}
protected void paintBorder(Graphics g)
{
int w = getSize().width;
int h = getSize().height;
int d = 50;
int r = d / 2;
g.setColor(this.getBackground().brighter());
g.drawLine(1, r, 1, h);
g.drawArc(1, 1, d, d, 180, -90);
g.drawLine(r, 1, w - r, 1);
g.drawArc(w - d - 1, 1, d, d, 0, 90);
g.drawLine(w - 1, r, w - 1, h);
g.drawLine(0, h - 1, w - 1, h - 1);
g.setColor(this.getBackground().darker());
g.drawLine(0, r, 0, h - 2);
g.drawArc(0, 0, d, d, 180, -90);
g.drawLine(r, 0, w - r, 0);
g.drawArc(w - d - 2, 0, d, d, 0, 90);
g.drawLine(w - 2, r, w - 2, h - 2);
g.drawLine(0, h - 2, w - 2, h - 2);
}
public static void main(String[] args)
{
JButton button = new RoundButton("圆形按钮");
// These statements enlarge the button so that it
// becomes a circle rather than an oval.
Dimension size = getPreferredSize();
// size.width = size.height = Math.max(size.width, size.height);
setPreferredSize(size);
// This call causes the JButton not to paint the background.
// This allows us to paint a round background.
setContentAreaFilled(false);
}
// Paint the round background and label.
protected void paintComponent(Graphics g) {
if (getModel().isArmed()) {
// You might want to make the highlight color
// a property of the RoundButton class.
g.setColor(Color.lightGray);
} else {
g.setColor(getBackground());
}
g.fillOval(0, 0, getSize().width-1, getSize().height-1);
// This call will paint the label and the focus rectangle.
super.paintComponent(g);
}
// Paint the border of the button using a simple stroke.
protected void paintBorder(Graphics g) {
g.setColor(getForeground());
g.drawOval(0, 0, getSize().width-1, getSize().height-1);
}
// Hit detection.
Shape shape;
public boolean contains(int x, int y) {
// If the button has changed size, make a new shape object.
if (shape == null || !shape.getBounds().equals(getBounds())) {
shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());
}
return shape.contains(x, y);
}
// Test routine.
public static void main(String[] args) {
// Create a button with the label.
JButton button = new RoundButton("圆形按钮");
JButton b2;
ImageIcon ic;
button.setBackground(Color.green);
// Create a frame in which to show the button.
ic = new ImageIcon("Red.GIF");
b2=new JButton(ic);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.yellow);
frame.getContentPane().add(button);
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(b2);
frame.setSize(300, 200);
frame.setVisible(true);
}
}