import java.awt.*; import java.awt.event.*; import javax.swing.*; public class BeepAndSquiggle extends JPanel implements ActionListener, MouseMotionListener { // the Beep button in the BeepAndSquiggle window private JButton beepButton = new JButton("Click to Beep"); private static final int NUM_POINTS = 40; private int curIndex = 0; private Point points[] = new Point[NUM_POINTS]; // constructor public BeepAndSquiggle() { add(beepButton); beepButton.addActionListener(this); addMouseMotionListener(this); for (int i=0; i < NUM_POINTS; i++) { points[i] = new Point(0,0); } } public void actionPerformed(ActionEvent e) { (new JButton()).getToolkit().beep(); } public void mouseDragged(MouseEvent e) { points[curIndex] = new Point(e.getX(), e.getY()); curIndex = (curIndex + 1) % NUM_POINTS; repaint(); } public void mouseMoved(MouseEvent e) { // take no action when the mouse is moved } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setColor(Color.BLACK); g2.setStroke(new BasicStroke(2)); for (int i=0; i < NUM_POINTS-1; i++) { g2.drawLine((int) points[(curIndex+i)%NUM_POINTS].getX(), (int) points[(curIndex+i)%NUM_POINTS].getY(), (int) points[(curIndex+i+1)%NUM_POINTS].getX(), (int) points[(curIndex+i+1)%NUM_POINTS].getY()); } } // main method that creates a new BeepAndSquiggle window public static void main(String[] args) { JFrame window = new JFrame("Beep and Squiggle"); BeepAndSquiggle panel = new BeepAndSquiggle(); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.getContentPane().add(panel); window.pack(); window.setBounds(250,250,250,250); window.setVisible(true); } }