// VariablesDemo2Panel.java
// Custom panel which demonstrates paint method and
// exemplifies difference between static and instance
// variables.
//
// Intended to be used with VariablesDemo2.java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* Custom panel which, whenever it is painted,
* talks to two separate text fields (not
* necessarily attached to this panel) to
* display up-to-date counts of (1) the
* number of objects of this class and
* (2) the number of times this panel has
* been painted. It also talks to the
* window's title bar to display count
* of panels of this class when this
* panel is created.
*
* @author D. Nixon
*/
public class VariablesDemo2Panel extends JPanel
{
/**
* Window which displays this panel
*/
private VariablesDemo2 window;
/**
* Count of times this panel has been painted
*/
private int paintCount = 0;
/**
* Count of objects of this class
*/
private static int objectCount = 0;
/**
* Creates a custom panel that can talk to
* the specified GUI components.
*
* @param window frame whose title bar will
* display count of objects of this
* class when this panel is created
* @param objectCountField text field that will
* display count of objects of this
* class when this panel is painted
* @param paintCountField text field that will
* display count of times this panel
* has been painted
*/
public VariablesDemo2Panel(VariablesDemo2 window)
{
// Enable this panel to talk to its window:
this.window = window;
// This panel hasn't been painted yet
paintCount = 0;
// Increment count of objects created
// via calls to this constructor.
VariablesDemo2Panel.objectCount++;
// Use window's title bar to display how many
// panels of this class have been created so far:
window.setTitle("Window #" + objectCount);
} // constructor
/**
* The paint method is called automatically
* whenever this panel is painted.
*
* @param g an object that can draw on this panel
*/
public void paint( Graphics g )
{
// Distances in pixels from top left corner of this panel
int pixelsFromLeft = 20;
int pixelsFromTop = 20;
// Dimensions, in pixels, of a big fat X to
// be drawn on this panel:
int width = 280;
int height = 130;
// Draw a red line from top left to bottom right
// of this panel:
g.setColor(Color.red);
g.drawLine(pixelsFromLeft, pixelsFromTop,
pixelsFromLeft + width, pixelsFromTop + height);
// Draw a blue line from top right to bottom left
// of this panel:
g.setColor(Color.blue);
g.drawLine(pixelsFromLeft + width, pixelsFromTop,
pixelsFromLeft, pixelsFromTop + height);
// Increment count of times this paint function
// has been called:
paintCount++;
// Display up-to-date messages in text fields:
window.setTopText("There are "
+ VariablesDemo2Panel.objectCount
+ " of us.");
window.setBottomText("I've been painted "
+ paintCount + " time"
+ ((paintCount==1)?"":"s")
+ ".");
} // method paint(Graphics)
} // class VariablesDemo2Panel