event

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");

  add(button);

  MenuBar menuBar = new MenuBar();

  setMenuBar(menuBar);

  Menu menu = new Menu("Menu");

  menuBar.add(menu);

  MenuItem menuItem = new MenuItem("Open");

  menu.add(menuItem);

  ActionListener saver = new ActionListener() {

@Override

public void actionPerformed(ActionEvent event) {

    System.out.println("Opening...");

}

  };

  // Register the actionListener with button

  button.addActionListener(saver);

  // And now register the same actionListener with menuItem

  menuItem.addActionListener(saver);

  pack();
    }

    private static void showUi() {

  ReuseListener reuseListener = new ReuseListener();

  reuseListener.setVisible(true);

    }

    public static void main(String[] a) {

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

@Override

public void run() {

    showUi();

}

  });

    }
}

 
This was an example now how to create Items with the same ActionListener 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