// Stuart Reges // 10/10/04 // // The DrawingPanel class provides a simple interface for drawing persistent // images using a Graphics object. An internal BufferedImage object is used // to keep track of what has been drawn. A client of the class simply // constructs a DrawingPanel of a particular size and then draws on it with // the Graphics object, setting the background color if they so choose. // // To ensure that the image is always displayed, a timer calls repaint at // regular intervals. import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.swing.*; public class DrawingPanel implements ActionListener { private JPanel myPanel; // overall drawing panel private BufferedImage myImage; // remembers drawing commands public static final int DELAY = 250; // delay between repaints in millis // construct a drawing panel of given width and height enclosed in a frame public DrawingPanel(int width, int height) { JFrame frame = new JFrame("CSE142 Drawing Panel"); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); myPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0)); myPanel.add(new JLabel(new ImageIcon(myImage))); frame.getContentPane().add(myPanel); myPanel.setPreferredSize(new Dimension(width, height)); frame.pack(); frame.setVisible(true); new Timer(DELAY, this).start(); } // obtain the Graphics object to draw on the panel public Graphics getGraphics() { Graphics2D g2 = (Graphics2D)myImage.getGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); return g2; } // set the background color of the drawing panel public void setBackground(Color c) { myPanel.setBackground(c); } // used for an internal timer that keeps repainting public void actionPerformed(ActionEvent e) { myPanel.repaint(); } }