// DrawingLinesPanelApplet.java (c) Kari Laitinen // http://www.naturalprogramming.com/ // 2006-01-20 File created. // 2007-02-28 Last modification. // This is the 'Panel' version of DrawingLinesApplet.java import java.awt.* ; import java.awt.event.*; import javax.swing.* ; class DrawingLinesPanel extends JPanel 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 DrawingLinesPanel() { // 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 paintComponent( Graphics graphics ) { // The superclass version of paintComponent() clears the // component area and does other necessary things. super.paintComponent( 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 ) ; } } } public class DrawingLinesPanelApplet extends JApplet { public void init() { getContentPane().add( new DrawingLinesPanel() ) ; } }