event

Multiple listeners example

In this example we are going to talk about how to work with multiple listeners in Java. This is particularly useful when you want to register more than one listeners in a single component, a button for instance.

All you have to do to work with multiple listeners is:

  • Create a class that extends JFrame and implements ActionListener.
  • Create an number of these JFrames and put them in an array. This array could easily hold any class as long as it implements the ActionListener interface.
  • Create a master JFrame component that has a JButton as a field. Then go through the array of the ActionListeners and use JButton.addActionListener method to register each on of them to the button.

Let’s take a closer look at the code snippets that follow:

package com.javacodegeeks.java.core;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class MultiWinListener {

	public static void main(String[] args) {

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

			@Override
			public void run() {

				showUI();

			}

		});

	}

	private static void showUI() {

		Two fr1 = new Two();

		fr1.setVisible(true);

		Two fr2 = new Two();

		fr2.setVisible(true);

		ActionListener[] broFrames = { fr1, fr2 };

		One f1 = new One(broFrames);

		f1.setVisible(true);

	}
}

class One extends JFrame {

	JButton button = new JButton("Press Here!");

	public One(ActionListener[] frs) {

		getContentPane().add(button);

		for (int c = 0; c < frs.length; c++) {

			button.addActionListener(frs);

		}
	}
}

class Two extends JFrame implements ActionListener {

	protected JLabel label = new JLabel("");

	public Two() {

		getContentPane().add(label);
	}

	@Override
	public void actionPerformed(ActionEvent event) {

		label.setText("OK");
	}
}

 
This was an example on how to work with Multiple Listeners in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron 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