//******************************************************************** // DrawPolylinePanel.java Programming with Alice and Java // // Solution to Programming Project 8.9 //******************************************************************** import javax.swing.*; import java.awt.*; import java.awt.event.*; public class DrawPolylinePanel extends JPanel { int[] xPoints, yPoints; int numPoints; //----------------------------------------------------------------- // Sets up the panel. Assumes there is no more than 100 // line segements in the polyline. //----------------------------------------------------------------- public DrawPolylinePanel () { setBackground (Color.black); xPoints = new int [100]; yPoints = new int [100]; numPoints = 0; addMouseListener (new MouseClickListener()); Button clearButton = new Button("Clear"); clearButton.addActionListener(new ButtonListener()); add(clearButton); } //----------------------------------------------------------------- // Draws the polyline //----------------------------------------------------------------- public void paintComponent (Graphics page) { super.paintComponent(page); page.setColor (Color.green); page.drawPolyline (xPoints, yPoints, numPoints); } //***************************************************************** // Represents the listener for the mouse clicks //***************************************************************** private class MouseClickListener extends MouseAdapter { //----------------------------------------------------------------- // Captures the end of the new line to add to the polygon. //----------------------------------------------------------------- public void mouseClicked (MouseEvent event) { xPoints [numPoints] = event.getX (); yPoints [numPoints] = event.getY (); numPoints++; repaint (); } } //***************************************************************** // Represents the listener for the clear button //***************************************************************** class ButtonListener implements ActionListener { public void actionPerformed (ActionEvent event) { numPoints = 0; repaint(); } } }