01: import java.awt.Color;
02: import java.awt.Graphics;
03: import java.awt.Graphics2D;
04: import java.awt.Rectangle;
05: import javax.swing.JComponent;
06: 
07: /**
08:    A component that shows a colored square.
09: */
10: public class ColoredSquareComponent extends JComponent
11: {  
12:    /**
13:       Constructs a component that shows a colored square.
14:       @param aColor the fill color for the square
15:    */
16:    public ColoredSquareComponent(Color aColor)
17:    {  
18:       fillColor = aColor;
19:    }
20:    
21:    public void paintComponent(Graphics g)
22:    {  
23:       Graphics2D g2 = (Graphics2D) g;
24: 
25:       // Select color into graphics context
26:    
27:       g2.setColor(fillColor);
28:       
29:       // Construct and fill a square whose center is
30:       // the center of the window
31: 
32:       final int SQUARE_LENGTH = 100;
33:       
34:       Rectangle square = new Rectangle(
35:             (getWidth() - SQUARE_LENGTH) / 2,
36:             (getHeight() - SQUARE_LENGTH) / 2,
37:             SQUARE_LENGTH,
38:             SQUARE_LENGTH);
39:          
40:       g2.fill(square);
41:    }
42:    
43:    private Color fillColor;
44: }