1 22 23 package demo.draw; 24 25 import java.awt.*; 26 import java.awt.event.*; 27 import java.awt.geom.*; 28 import java.awt.image.*; 29 import java.awt.print.*; 30 import java.util.*; 31 import javax.swing.*; 32 33 public class Canvas extends JPanel implements Printable 34 { 35 private ArrayList _lines = new ArrayList(); 36 37 private Line2D _newLine = null; 38 39 private BasicStroke _stroke = new BasicStroke( 7, 40 BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND ); 41 42 public Canvas() 43 { 44 addMouseListener( 45 new MouseListener() 46 { 47 public void mouseClicked( MouseEvent ev ) { } 48 49 public void mouseEntered( MouseEvent ev ) { } 50 51 public void mouseExited( MouseEvent ev ) { } 52 53 public void mousePressed( MouseEvent ev ) 54 { 55 startDrawingLine( ev.getX(), ev.getY() ); 56 } 57 58 public void mouseReleased( MouseEvent ev ) 59 { 60 endDrawingLine(); 61 } 62 } ); 63 64 addMouseMotionListener( 65 new MouseMotionListener() 66 { 67 public void mouseDragged( MouseEvent ev ) 68 { 69 updateDrawingLine( ev.getX(), ev.getY() ); 70 } 71 72 public void mouseMoved( MouseEvent ev ) { } 73 } ); 74 } 75 76 public Image getImage() 77 { 78 int width = getWidth(); 79 int height = getHeight(); 80 BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB ); 81 Graphics2D g2 = ( Graphics2D ) image.getGraphics(); 82 paintComponent( g2 ); 83 return image; 84 } 85 86 public java.util.List getLines() 87 { 88 return _lines; 89 } 90 91 public void clear() 92 { 93 _lines.clear(); 94 repaint(); 95 } 96 97 public void paintComponent( Graphics g ) 98 { 99 Graphics2D g2 = ( Graphics2D ) g; 100 101 g2.setStroke( _stroke ); 102 103 int width = getWidth(); 104 int height = getHeight(); 105 106 g2.setColor( Color.YELLOW ); 108 g2.fillRect( 0, 0, width - 1, height - 1 ); 109 110 g2.setColor( Color.BLACK ); 112 for( Iterator it = _lines.iterator(); it.hasNext(); ) 113 { 114 Line2D line = ( Line2D ) it.next(); 115 g2.draw( line ); 116 } 117 } 118 119 public int print( Graphics graphics, PageFormat pageFormat, int pageIndex ) 120 throws PrinterException 121 { 122 paintComponent( graphics ); 123 return Printable.PAGE_EXISTS; 124 } 125 126 private void endDrawingLine() 127 { 128 _newLine = null; 129 } 130 131 private void startDrawingLine( int x, int y ) 132 { 133 _newLine = new Line2D.Double( x, y, x, y ); 134 _lines.add( _newLine ); 135 136 repaint(); 137 } 138 139 private void updateDrawingLine( int x, int y ) 140 { 141 if( _newLine == null ) 142 return; 143 144 _newLine.setLine( _newLine.getX1(), _newLine.getY1(), x, y ); 145 repaint(); 146 } 147 } 148 | Popular Tags |