Assume that a class has an inner class named MyTimerListener that can be used to
ID: 3882876 • Letter: A
Question
Assume that a class has an inner class named MyTimerListener that can be used to handle the events generated by a Timer object. Write code that creates a Timer object with a time delay of one half second. Register an instance of MyTimerListener with the class.
Is this right??
public class MyTimerListener extends JApplet
{
private final int TIME_DELAY = 1500;
private Time timer;
public void init()
{
timer = new Timer (TIME_DELAY, new TimerListener());
timer.start();
}
public class TImerListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
....
}
}
Explanation / Answer
I would like to add something on this code snippet..
The very first thing is MyTimerListener is an inner class. Inner class means a class within another class. So you should have defined it in this way..
public class TimerListener extends JApplet
{
private final int TIME_DELAY = 1500;
private Time timer;
public void init()
{
timer = new Timer (TIME_DELAY, new MyTimerListener());
timer.start();
}
//inner class
public class MyTimerListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
....
}
}
}
I've only changed the 2 class names in order to fulfill the requirements.
The timer constructor takes in the time as milliseconds so yes 1500 is correct for 1.5 seconds.
You have to register the object with MyTimerListener so the second parameter in constructor is an object of that class.
So your code is correct, just swap the class names.
If there's any query, do comment. I'll address it.
Thank you.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.