// DrawingLinesAWTApplet.java (c) 2000 Kari Laitinen // http://www.naturalprogramming.com/ // 2000-??-?? File created. // 2007-02-28 Last modification. import java.awt.* ; import java.awt.event.*; public class DrawingLinesAWTApplet extends java.applet.Applet implements MouseListener, MouseMotionListener { final int MAXIMUM_NUMBER_OF_LINES = 10 ; Point[] starting_points = new Point[ MAXIMUM_NUMBER_OF_LINES ] ; Point[] ending_points = new Point[ MAXIMUM_NUMBER_OF_LINES ] ; Point start_of_new_line ; Point end_of_new_line ; int number_of_lines = 0 ; public void init() { setBackground(Color.white); // Event listeners must be registered. addMouseListener(this); addMouseMotionListener(this); } // The following dummy methods are needed // to fully implement the listener interfaces. public void mouseMoved( MouseEvent event ) {} public void mouseClicked( MouseEvent event ) {} public void mouseEntered( MouseEvent event ) {} public void mouseExited( MouseEvent event ) {} public void mousePressed( MouseEvent event ) { if ( number_of_lines < MAXIMUM_NUMBER_OF_LINES ) { start_of_new_line = event.getPoint() ; } } public void mouseReleased( MouseEvent event ) { if ( number_of_lines < MAXIMUM_NUMBER_OF_LINES ) { starting_points[ number_of_lines ] = start_of_new_line; ending_points[ number_of_lines ] = event.getPoint() ; number_of_lines ++ ; end_of_new_line = null ; start_of_new_line = null ; repaint() ; } } public void mouseDragged( MouseEvent event ) { if ( number_of_lines < MAXIMUM_NUMBER_OF_LINES ) { end_of_new_line = event.getPoint() ; repaint(); } } public void paint( Graphics graphics ) { for ( int line_index = 0 ; line_index < number_of_lines ; line_index ++ ) { graphics.drawLine( starting_points[ line_index ].x, starting_points[ line_index ].y, ending_points[ line_index ].x, ending_points[ line_index ].y ) ; } graphics.setColor( Color.red ) ; if ( end_of_new_line != null ) { graphics.drawLine( start_of_new_line.x, start_of_new_line.y, end_of_new_line.x, end_of_new_line.y ) ; } if ( number_of_lines == MAXIMUM_NUMBER_OF_LINES ) { graphics.drawString( "Cannot draw more lines", 0, 300 ) ; } } }