Items with the same ActionListener

With this tutorial we are going to show you how to create several items with the same ActionListener. This is very useful when you want a number of components to behave in the same way under the occurrence of certain events.

It’s very easy to add this kind of functionality in your Application. You simply:

  • Create the items you want
  • Create a class that implements ActionListener interface and override the actionPerfomed method.
  • And then just use the addActionListener method of each component to bundle them with the ActionListener you’ve created.

Let’s take a look at the code:

package com.javacodegeeks.snippets.desktop;

import java.awt.Button;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ReuseListener extends Frame {

    public ReuseListener() {

  Button button = new Button("Open");


  MenuBar menuBar = new MenuBar();


  Menu menu = new Menu("Menu");


  MenuItem menuItem = new MenuItem("Open");


  ActionListener saver = new ActionListener() {


public void actionPerformed(ActionEvent event) {




  // Register the actionListener with button


  // And now register the same actionListener with menuItem



    private static void showUi() {

  ReuseListener reuseListener = new ReuseListener();



    public static void main(String[] a) {

  javax.swing.SwingUtilities.invokeLater(new Runnable() {


public void run() {





This was an example now how to create Items with the same ActionListener in Java.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Ilias Tsagklis

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

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

Inline Feedbacks
View all comments
Back to top button