Multicast event example

In this tutorial we are going to see how to manage multicast events. Multicast events are quite useful when you have to work with many windows in your application and you just want to perform the same action or a group of actions in a number of windows in your application at the same time.

For example, if the user have opened many windows in the application, you might want to provide a command that closes all the windows at once.

In order to work with multicast events you have to:

  • Create a class that extends JPanel and implements ActionListener. This class should have a JButton component as a private member. This will be the button that will give the command to all the windows.
  • Override the actionPerformed method of this class to bundle a second button that performs a specific action. In our case the creation of a new window.
  • The new windows that will be launched will also implement ActionListener.
  • We will register the new ActionListeners to the button that gives the command to all the windows. So, now when this button is pressed all ActionListeners that are resistered to it will be launched and their actionPerformed method will be executed

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

package com.javacodegeeks.snippets.desktop;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MulticastEvent extends JPanel implements ActionListener {

    private int cnt = 0;
    private JButton closeAllButton;

    public MulticastEvent() {

  JButton jButton = new JButton("New");



  closeAllButton = new JButton("Close all");


    public void actionPerformed(ActionEvent event) {

  CloseFrame closeFrame = new CloseFrame();


  closeFrame.setTitle("Window " + cnt);

  closeFrame.setSize(200, 150);

  closeFrame.setLocation(30 * cnt, 30 * cnt);



    private static void showUI() {

  JFrame jFrame = new JFrame();


  jFrame.setSize(700, 500);

  jFrame.addWindowListener(new WindowAdapter() {


public void windowClosing(WindowEvent event) {




  Container cPane = jFrame.getContentPane();

  cPane.add(new MulticastEvent());


    class CloseFrame extends JFrame implements ActionListener {


  public void actionPerformed(ActionEvent evt) {



    public static void main(String[] args) {

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


public void run() {




This was an example on how to work with multicast events in Java.

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