// version 1b = version 1a + program does double-buffering import java.awt.image.* ; import java.awt.* ; import java.awt.event.* ; import javax.swing.* ; /** * The draw application. */ public class Draw extends JFrame { /** * The easel for this application. */ private DrawPanel panel ; public Draw() { super("Draw") ; // create menubar // create toolbar panel = new DrawPanel() ; panel.setBackground(Color.white) ; // add components to toolbar this.setLayout(new BorderLayout()) ; this.getContentPane().add("Center", panel) ; this.setVisible(true) ; this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE) ; // exitExam() } public static void main(String[] args) { Draw draw = new Draw() ; draw.setSize(300,375) ; draw.setLocation(500,500) ; draw.setVisible(true) ; } } ////////////////////////////////////////////////// /** * The drawing panel. */ class DrawPanel extends JPanel implements MouseListener, MouseMotionListener { private Point pivot ; // mark mouse down private int lastx, lasty ; // for dragging private BufferedImage buffer ; // off-screen drawing buffer BasicStroke stroke ; public DrawPanel() { this.addMouseListener(this) ; this.addMouseMotionListener(this) ; pivot = new Point() ; buffer = new BufferedImage(1000,1000,BufferedImage.TYPE_INT_RGB) ; Graphics g = buffer.getGraphics() ; g.setColor(Color.WHITE) ; g.fillRect(0,0,1000,1000) ; // set background for buffer to white // test stroke stroke = new BasicStroke(3) ; } // MouseListener public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) { // mark mouse down pivot.x = e.getX() ; pivot.y = e.getY() ; lastx = pivot.x ; lasty = pivot.y ; } public void mouseReleased(MouseEvent e) {} // MouseMotionListener public void mouseMoved(MouseEvent e) {} public void mouseDragged(MouseEvent e) { Graphics2D g = (Graphics2D)buffer.getGraphics() ; // off-screen g.setStroke(stroke) ; if (e.isShiftDown()) { // straight line //erase last rubber banding g.setColor(this.getBackground()) ; g.drawLine(pivot.x,pivot.y,lastx,lasty) ; // draw new rubber banding g.setColor(Color.black) ; g.drawLine(pivot.x,pivot.y,e.getX(),e.getY()) ; lastx = e.getX() ; lasty = e.getY() ; } else { // "demonstrate scattering" // draw new rubber banding g.setColor(Color.black) ; g.drawRect(e.getX(),e.getY(),2,2) ; } // on-screen Graphics ong = this.getGraphics() ; ong.drawImage(buffer,0,0,this) ; } public void paintComponent(Graphics g) { g.drawImage(buffer,0,0,this) ; } }