// CS7 - // RandomPaint allows the user to click & drag the mouse drawing lines // along the way. A click of the button will change the color of the lines // randomly. import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import java.applet.*; public class RandomPaint extends JApplet { // class variables (to hold mouse coordinates) private int last_x = 0, last_y = 0; private int now_x = 0, now_y = 0; // the graphics context private Graphics g; public void init() { // colors final Color [] someColors = { Color.black, Color.red, Color.green, Color.blue, Color.magenta }; // get access to the applet's top-level container Container pane = getContentPane(); // load the graphics context g = getGraphics(); // create components final JButton flipButton = new JButton("Change Color"); // add the button pane.setLayout(new FlowLayout()); // java fits things in for you pane.add(flipButton); // when the button is pressed, pick a new color randomly flipButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // randomly pick a color from the array g.setColor(someColors[(int)(Math.random()*10) % someColors.length]); } }); // This mouse listener just waits for mouse click events ("down"). // When it happens, we simply remember where the mouse is now. addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { last_x = e.getX(); last_y = e.getY(); } }); // This listener detects a drag event. // By calling repaint(), our paint() method is called, therefore drawing // a bunch of small lines. It appears pretty smooth for the user. addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { now_x = e.getX(); now_y = e.getY(); g.drawLine(last_x, last_y, now_x, now_y); last_x = now_x; // we now have "new" old locations last_y = now_y; } }); } // end init() } // end of class