import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import javax.swing.JPanel; import java.awt.event.MouseMotionAdapter; import java.awt.event.MouseEvent; import javax.swing.event.MouseInputAdapter; import java.util.ArrayDeque; class Whiteboard extends JPanel { private ArrayDeque<DrawnLine> lines = new ArrayDeque<DrawnLine>(); private ArrayDeque<DrawnLine> undoQueue = new ArrayDeque<DrawnLine>(); Point start = null; Point end = null; public void setStart(Point p) {this.start = p; } public Point getStart() {return this.start;} public Whiteboard() { setBackground(Color.white); addMouseListener(new MyMouseListener()); addMouseMotionListener(new MyMouseMotionAdapter()); } // Used for painting the pixels protected synchronized void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.black); // Iterator<DrawnLine> i = lines.iterator(); for ( DrawnLine dl: lines) { // while(i.hasNext()) { // DrawnLine dl = (DrawnLine) i.next(); g.setColor(dl.getColor()); g.drawLine(dl.getStart().x, dl.getStart().y, dl.getEnd().x, dl.getEnd().y); } } /** Add a line to the list of lines, and repaint the window */ protected synchronized void addDrawnLine(DrawnLine dl) { lines.add(dl); repaint(); } public synchronized void undo() { if (lines.isEmpty()) return; DrawnLine dl = lines.removeLast(); undoQueue.add(dl); repaint(); } public synchronized void redo() { if (undo.isEmpty()) return; DrawnLine dl = undo.remove(); lines.add(dl); repaint(); } /** Handles to pressing and releasing the mouse */ private class MyMouseListener extends MouseInputAdapter { public void mousePressed(MouseEvent me) { Point p= me.getPoint(); setStart (p); } public void mouseReleased(MouseEvent me) { Point p= me.getPoint(); if (start!=null) addDrawnLine(new DrawnLine(getStart(), p, java.awt.Color.RED)); setStart (null); } } /** Handles dragging the mouse */ private class MyMouseMotionAdapter extends MouseMotionAdapter { public void mouseDragged(MouseEvent me) { Point p = me.getPoint(); if (start!=null) addDrawnLine(new DrawnLine(getStart(), p, java.awt.Color.GREEN)); setStart(p); } } } // class Whiteboard