add Mouse Listener To All Component - Java Swing

Java examples for Swing:Mouse Event

Description

add Mouse Listener To All Component

Demo Code


//package com.java2s;
import java.awt.Component;
import java.awt.Container;

import java.awt.event.MouseListener;

import javax.swing.AbstractButton;
import javax.swing.JComponent;

public class Main {
    public static void addMouseListenerToAll(Component parent,
            MouseListener listener) {
        if (parent instanceof AbstractButton) {
            AbstractButton a = (AbstractButton) parent;
            boolean is = false;
            MouseListener[] kl = a.getMouseListeners();
            for (MouseListener k : kl) {
                if (k.equals(listener)) {
                    is = true;/* ww  w .j a  v a 2  s  .com*/
                    break;
                }
            }
            if (!is)
                a.addMouseListener(listener);
        }

        else if (parent instanceof JComponent) {
            JComponent a = (JComponent) parent;
            boolean is = false;
            MouseListener[] kl = a.getMouseListeners();
            for (MouseListener k : kl) {
                if (k.equals(listener)) {
                    is = true;
                    break;
                }
            }
            if (!is)
                a.addMouseListener(listener);
        }

        if (parent instanceof Container) {
            Component[] comps = ((Container) parent).getComponents();
            for (Component c : comps) {
                addMouseListenerToAll(c, listener);
            }
        }
    }
}

Related Tutorials