// PaintDemoPanel.java
// Custom panel which demonstrates paint method.
//
// Intended to be used with PaintDemo.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 unique ID numbers for (1) this
* panel itself and (2) this panel's current
* Graphics object.
*
* @author D. Nixon
*/
public class PaintDemoPanel extends JPanel
{
/**
* Text field for display of unique ID number
* for this panel object
*/
private JTextField panelObjectNumberField;
/**
* Text field for display of unique ID number
* for this panel's current Graphics object
*/
private JTextField graphicsObjectNumberField;
/**
* Creates a custom panel that can talk to
* the specified text fields.
*
* @param panelNumberField text field that will
* display a unique ID number for this panel
* @param graphicsNumberField text field that will
* display a unique ID number for this panel's
* current Graphics object
*/
public PaintDemoPanel(JTextField panelNumberField,
JTextField graphicsNumberField)
{
// Enable this panel to talk to text fields:
panelObjectNumberField = panelNumberField;
graphicsObjectNumberField = graphicsNumberField;
} // 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);
// Display up-to-date messages in text fields:
panelObjectNumberField.setText("The fat X is on a panel,"
+ " object #"
+ hashCode() + ".");
graphicsObjectNumberField.setText("Panel painted using"
+ " Graphics object #"
+ g.hashCode() + ".");
} // method paint(Graphics)
} // class PaintDemoPanel