Question: (Screen Saver Using Timer) Package javax.swing contains a class called Timer that is capable of calling method actionPerformed of interface ActionListener at a fixed time

(Screen Saver Using Timer) Package javax.swing contains a class called Timer that is capable of calling method actionPerformed of interface ActionListener at a fixed time interval (specified in milliseconds). Modify your solution to Exercise 13.18 to remove the call to repaint from method paintComponent. Declare your class to implement ActionListener. (The actionPerformed method should simply call repaint.) Declare an instance variable of type Timer called timer in your class. In the constructor for your class, write the following statements: timer = new Timer(1000, this); timer.start(); This creates an instance of class Timer that will call this objects actionPerformed method every 1000 milliseconds (i.e., every second).

you may use those hint:

// Program simulates a simple screen saver

import java.awt.Color;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

import java.awt.Graphics;

import java.util.Random;

import javax.swing.JPanel;

import javax.swing.Timer;

public class SaverJPanel extends JPanel implements ActionListener

{

// random-number generator

private static final Random random = new Random();

private Timer timer;

// constructor sets window's title bar string and dimensions

public SaverJPanel()

{

timer = new Timer( 1000, this ); // create the timer, every 1000 milliseconds, the timer triggers an event on the panel

timer.start();

} // end SaverJPanel constructor

// draw lines

public void paintComponent( Graphics g )

{

super.paintComponent( g );

int x, y, x1, y1;

//TO DO:

//Use for loop to draw 100 lines

//select x, y, x1, y1 coordinates to be random numbers between 0 and 300

//set color to be random RGB value

//call graphics draw line between point (x,y) and point(x1, y1)

} // end method paintComponent

// repaint JPanel

public void actionPerformed( ActionEvent actionEvent )

{

repaint();

} // end method actionPerformed

} // end class SaverJPanel

import javax.swing.JFrame;

public class Saver2

{

public static void main( String args[] )

{

// create frame for SaverJPanel

// set default close operation

// create new SaverJPanel

// add saverJPanel to frame

// set frame size (300, 300)

// display frame

} // end main

} // end class Saver2

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!