// CS7 - // ColorMessage displays a text message and allows the user to change the // color of the text by clicking on a button. import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import java.applet.*; public class ColorMessage extends JApplet { 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(); // create components final JButton flipButton = new JButton("Change Color"); // flow layout just tells java to fit stuff in as it is added pane.setLayout(new FlowLayout()); // java fits things in for you pane.add(flipButton); // add the listener flipButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // allows you to paint in the applet, through g Graphics g = getGraphics(); // randomly pick a color from the array setForeground(someColors[(int)(Math.random()*10) % someColors.length]); repaint(); // tells java to paint again } }); } // end init() // this method is automatically called by java when a repaint() is called. // The graphics context is automatically passed in as a parameter // we must call the parent class ("super") paint() to make sure other // components (like the button) are also painted. If you don't call it, // the button is not repainted (try it!) public void paint(Graphics g) { super.paint(g); g.drawString("I know you are but what am I?", 20, 75); } } // end of class