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 implementsActionListener
. - Create an number of these
JFrames
and put them in an array. This array could easily hold any class as long as it implements theActionListener
interface. - Create a master
JFrame
component that has aJButton
as a field. Then go through the array of theActionListeners
and useJButton.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.