// version 1 = version 0 + some drawing 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 public DrawPanel() { this.addMouseListener(this) ; this.addMouseMotionListener(this) ; pivot = new Point() ; } // 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) { if (e.isShiftDown()) { // straight line Graphics g = this.getGraphics() ; //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() ; } } }