import java.awt.*; import javax.swing.*; /** The class represents Swing based graphics device. */ class SwingGraphics implements TGraphics { private char[][] display; private int width, height; private SwingCanvas canvas; private Container pane; private JFrame frame; private Graphics g; /** Construct a graphics object for a console with the specified dimensions. @param width - the width of the drawable area in characters. @param height - the height of the drawable area in characters. */ SwingGraphics(int width, int height) { frame = new JFrame(); pane = frame.getContentPane(); canvas = new SwingCanvas(width, height); pane.setBackground(Color.white); pane.add(canvas); this.width = width; this.height = height; frame.pack(); frame.show(); g = canvas.getGraphics(); getDrawingGraphics(); } /** Draw a line from (x1, y1) to (x2, y2). @param x1 - x coordinate of first point. @param y1 - y coordinate of first point. @param x2 - x coordinate of second point. @param y2 - y coordinate of second point. */ public void drawLine(int x1, int y1, int x2, int y2) { offscreenGraphics.drawLine(x1, y1, x2, y2); } /** Copy what has been drawn onto the display to the console. */ public void render() { g.drawImage(offscreenImage,0,0,width,height,null); offscreenGraphics.setColor(Color.white); offscreenGraphics.fillRect(0,0,width, height); // mimic a device that forgets offscreenGraphics.setColor(Color.black); } /** Clear the display. */ public void clear() { Color save = g.getColor(); g.setColor(Color.white); g.fillRect(0,0,width, height); g.setColor(save); } /** Make the offscreen image if one doesn't exist. This must be called AFTER the canvas has been created an initially displayed. */ private void getDrawingGraphics() { if (offscreenGraphics == null) { offscreenImage = canvas.createImage(width, height); offscreenGraphics = offscreenImage.getGraphics(); } } private Image offscreenImage; private Graphics offscreenGraphics; }