public class RoundButton extends JButton
1: //RoundButton.java
2: //Based on an example found on the Sun web site.
4: import java.awt.*;
5: import java.awt.geom.*;
6: import javax.swing.*;
8: public class RoundButton extends JButton
9: {
10: public static void main(String[] args)
11: {
12: //Create a button with the label "Jackpot".
13: JButton button = new RoundButton("Jackpot");
14: button.setBackground(Color.green);
16: //Create a frame in which to show the button.
17: JFrame frame = new JFrame();
18: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
19: frame.getContentPane().setLayout(new FlowLayout());
20: frame.getContentPane().setBackground(Color.yellow);
21: frame.getContentPane().add(button);
22: frame.setSize(150, 120);
23: frame.setVisible(true);
24: }
26: public RoundButton(String label)
27: {
28: super(label);
30: //Enlarge button to make a circle rather than an oval.
31: Dimension size = getPreferredSize();
32: size.width = size.height = Math.max(size.width, size.height);
33: setPreferredSize(size);
35: //This call causes the JButton *not* to paint the background
36: //and allows us to paint a round background instead.
37: setContentAreaFilled(false);
38: }
40: //Paint the round background and label.
41: protected void paintComponent(Graphics g)
42: {
43: if (getModel().isArmed())
44: //You might want to make the highlight color
45: //a property of the RoundButton class.
46: g.setColor(Color.lightGray);
47: else
48: g.setColor(getBackground());
49: g.fillOval(0, 0, getSize().width-1, getSize().height-1);
50: //This call will paint label and focus rectangle.
51: super.paintComponent(g);
52: }
54: //Paint the border of the button using a simple stroke.
55: protected void paintBorder(Graphics g)
56: {
57: g.setColor(getForeground());
58: g.drawOval(0, 0, getSize().width-1, getSize().height-1);
59: }
60: }