Question
Program:
//Displays a frame containing a single button. Pressing the
//button causes the background of the frame to change Color Randomly
import java.util.Random;
import java.awt.*;
import java.awt.event.*;
//Driver class
public class ChangingColor {
public static void main(String[] args) {
Frame f = new ChangeColorFrame("Random Colors");
f.setSize(160, 100);
f.setVisible(true);
}
}
//Frame class
class ChangeColorFrame extends Frame {
public ChangeColorFrame(String title) {
// Set title, layout, and background color
super(title);
setLayout(null);
setBackground(Color.white);
// Add "Change color" button to frame and attach listener
Button b = new Button("Random");
b.setBounds(60, 60, 60, 30);;
add(b);
b.addActionListener(new ButtonListener());
// Attach window listener
addWindowListener(new WindowCloser());
}
//Listener for button
class ButtonListener implements ActionListener {
Random rand=new Random();
public void actionPerformed(ActionEvent evt) {
int i=rand.nextInt(256);
int j=rand.nextInt(256);
int k=rand.nextInt(256);
Color c = new Color(i, j, k);
setBackground(c);
}
}
//Listener for window
class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
}
}
0 comments:
Post a Comment