1    import javax.swing.*;
2    import java.awt.event.*;
3    import java.awt.*;
4    import java.util.*;
5    
6    public class ColorBox extends JButton implements ActionListener {
7    
8      public Color color = Color.black;
9    
10     public ColorBox(Color c,String l) {
11       setPreferredSize(new Dimension(200,50));
12       setText(l);
13       color = c;
14       addActionListener(this);
15       setContentAreaFilled(true);
16     }
17   
18     public void paintComponent(Graphics g) {
19       Color c = g.getColor();
20       Color buttoncolor = color;
21       if (buttoncolor==null) buttoncolor=Color.black;
22       g.setColor(buttoncolor);
23       Rectangle r = getBounds();
24       g.fillRect(0,0,r.width,r.height);
25       int bright = buttoncolor.getBlue() + buttoncolor.getRed() + buttoncolor.getGreen();
26       if (bright>389)
27         g.setColor(Color.black);
28       else
29         g.setColor(Color.white);
30       g.drawString(getText(),25,25);
31       g.setColor(c);
32     }
33   
34     public void actionPerformed(ActionEvent e) {
35       color = JColorChooser.showDialog(this,getText(),color);
36     }
37   }
38