class

Anonymous inner class – Part 2

This is an example of how to use an anonymous inner class. We have created a class, TalkingClock, that is a clock that prints the time in regular intervals and use it in another class, as described in the following steps:

  • TalkingClock has a method start(int interval, final boolean beat). The method creates a new ActionListener object that overrides the actionPerformed(ActionEvent event) of the ActionListener interface. This method will be invoked when the action will occur. In this method a new Date object is created and an audio beep is emitted, with beep() API method of Toolkit.
  • A new Timer is created in the start(int interval, final boolean beat) method to fire the ActionEvent at a given interval and its start() method is used.
  • We create a new instance of TalkingClock and call its start(int interval, final boolean beat) method.
  • We also bring up an information-message dialog titled with the message “Quit Program?”, using showMessageDialog(Component parentComponent, Object message) API method of JOptionPane.
  • The program will keep running until the user selects OK. Then the System.exit(0) to end the application.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.Timer;

public class AnonymousInnerClassTest {

    public static void main(String[] args) {

  

  TalkingClock timer = new TalkingClock();

  timer.start(1000, true);


  // keep program running until user selects "Ok"

  JOptionPane.showMessageDialog(null, "Quit program?");

  System.exit(0);
    }
}
/**
 * A clock that prints the time in regular intervals.
 */
class TalkingClock {
    /**
     * Starts the clock.
     *
     */
    public void start(int interval, final boolean beat) {

  ActionListener listener = new ActionListener() {



@Override


public void actionPerformed(ActionEvent event) {


    Date now = new Date();


    System.out.println("The time is " + now);


    


    if (beat){



  Toolkit.getDefaultToolkit().beep();


    }


}

  };

  Timer timer= new Timer(interval, listener);

  timer.start();
    }
}

  
This was an example of how to use an anonymous inner class in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button