previous | start | next

File RectanglePanel.java

1 import java.awt.Dimension;
2 import java.awt.Graphics;
3 import java.awt.Graphics2D;
4 import java.awt.Rectangle;
5 import javax.swing.JPanel;
6
7 /**
8     This panel displays a rectangle.
9 */
10 public class RectanglePanel extends JPanel
11 {  
12    /**
13        Constructs a rectangle panel with the rectangle at a 
14        default location.
15     */
16    public RectanglePanel()
17    {  
18       setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
19       // the rectangle that the paint method draws
20       box = new Rectangle(BOX_X, BOX_Y, 
21          BOX_WIDTH, BOX_HEIGHT);
22    }
23
24    /**
25        Sets the location of the rectangle and repaints the panel.
26       @param x the x-coordinate of the top left corner of the rectangle
27       @param y the y-coordinate of the top left corner of the rectangle
28     */
29    public void setLocation(int x, int y)
30    {
31       box.setLocation(x, y);
32       repaint();
33    }
34
35    public void paintComponent(Graphics g)
36    {  
37       super.paintComponent(g);
38       Graphics2D g2 = (Graphics2D)g;
39       g2.draw(box);
40    }
41
42    private Rectangle box;
43    private static final int BOX_X = 100;
44    private static final int BOX_Y = 100;
45    private static final int BOX_WIDTH = 20;
46    private static final int BOX_HEIGHT = 30;
47
48    private static final int PANEL_WIDTH = 300;
49    private static final int PANEL_HEIGHT = 300;
50 }


previous | start | next