Java Reference
In-Depth Information
/** A JPanel of size (WIDTH, HEIGHT) with no components. Green or red depending on whether
the sum of the parameters of the constructor is even. Click square to produce a pink disk on it;
click again to remove the disk. */
public class Square extends JPanel {
/** Height and width of square */
public static final int HEIGHT= 50;
public static final int WIDTH= 50;
private int x; /* x-coordinate of square on board */
private int y; /* y-coordinate of square on board */
private boolean hasDisk= false ; /* = "the square has a pink disk" */
/** Constructor: a square at (x, y) */
public Square( int x, int y) {
this .x= x; this .y= y;
setPreferredSize( new Dimension(WIDTH, HEIGHT));
this .addMouseListener(new MouseEvents());
}
/** paint this square using g */
public void paint(Graphics g) {
if ((x+y)%2 == 0) { g.setColor(Color.green); }
else { g.setColor(Color.red); }
g.fillRect(0, 0, WIDTH -1,HEIGHT-1);
if (hasDisk) {
g.setColor(Color.pink);
g.fillOval(7, 7, WIDTH - 14, HEIGHT - 14);
}
g.setColor(Color.black);
g.drawRect(0, 0, WIDTH -1,HEIGHT-1);
g.drawString("(" + x + ", " + y + ")", 10, 5 + HEIGHT / 2);
}
/** Complement the "has pink disk" property */
public void complementDisk() { hasDisk= !hasDisk; repaint(); }
/** Remove pink disk (if present) */
public void clearDisk() { hasDisk= false ; repaint(); }
/** Contains methods that process mouse events */
public class MouseEvents extends MouseInputAdapter {
/** Complement the "has pink disk" property */
public void mouseClicked(MouseEvent e) { complementDisk(); }
}
}
Figure 17.16:
Class Square
Search WWH ::




Custom Search