1

I have 20 JLabels and all of them have to change their background color when mouse enters and change back to original color when mouse outs.

Do I have to individually bind 2 Event-listeners of MouseEntered and MouseExited with all JLabels separately, or is there any work around so I can make just 2 events kind of monitoring all JLabels?

Like in the image below: there are about 6 JLabels and I want each one to change its background color whenever the mouse enters the scene and change back to original color when the mouse outs.

enter image description here

So, do I have to individually set event listeners on all JLabels, or there can be a single event listener for all JLabels?

bruno
  • 2,213
  • 1
  • 19
  • 31
Airy
  • 5,484
  • 7
  • 53
  • 78

4 Answers4

2

You can register all 20 JLabels with the same mouse listener. You would do something like this:

MouseListener m = new MouseAdapter() // create our own mouse listener
{
    @Override
    public void mouseEntered(MouseEvent e) 
    {
         e.getComponent().setBackground(Color.RED);; // this method changes the colours of all the labels
    }
    @Override
    public void mouseExited(MouseEvent e)
    {
        e.getComponent().setBackground(Color.GREEN); // this method changes the colours back to normal
    }
};
for (JLabel label: labels) // iterate over all the labels
{
    label.addMouseListener(m); // give them all our mouse listener
}

Where "labels" is some collection (List, Set, array...) of your JLabels, and changeLabelColours() and changeLabelColoursBack() are two methods that you define to change the colours.

hope this helps!

EDIT: reading your edited question, I think I should point out that this code will cause ALL labels to change colour when ANY of the labels is moused-over. I think that's what you mean.

Airy
  • 5,484
  • 7
  • 53
  • 78
Nekojimi
  • 118
  • 10
  • This could be really useful in the very near future for me. Thanks! +1. What if a slightly different mouse listener was needed for each JLabel? How would you do it individually? – Joehot200 Sep 12 '14 at 12:48
  • Iterating is showing some error. would you look at that please? – Airy Sep 12 '14 at 12:50
  • Ok let me give it a try hold on – Airy Sep 12 '14 at 12:51
  • 1
    Joehot200: if you wanted to define object-specific behaviour for each object, you can use anonymous classes to do it: something like `for (JLabel label: labels){ label.addMouseListener(new MouseAdapter() {...}) }` this would give each label it's own, individual listener, and any functions overridden in the {...} block can use `label` to refer to the individual label. – Nekojimi Sep 12 '14 at 12:54
  • Abdul Jabbar WebBestow: remember, you will need to provide your own collection of your JLabels; my code posted there will not function on it's own. Also, if you want individual behavior per label, see my comment above. – Nekojimi Sep 12 '14 at 12:57
  • Nekojimi I addedMouseListener to all of JLabels and listner is working good just like you said but how can I change color of JLabel? for testing this I wrote this line System.out.println("Mouse Entered"); and its working but how can I change label color – Airy Sep 12 '14 at 13:02
  • Try `JLabel.setBackground(Color bg)` – Nekojimi Sep 12 '14 at 13:06
  • Noop Not working. I also tried putting just setBackground but not working. – Airy Sep 12 '14 at 13:09
0

You don't "make events". You make eventListeners. And yes, you can do just 2 event listeners and bound them to all JLabels.

Or, if you prefer, you can extends Jlabel into MyJlabel, that has the event listener built in, and save yourself from the repeated binding, if it bothers you.

bruno
  • 2,213
  • 1
  • 19
  • 31
0

You can use one MouseListener reference.

You should differentiate event sources based on references or on component name.

Here is an example

final JLabel label1 = new JLabel("label1");
label1.setName("label1");
final JLabel label2 = new JLabel("label2");
label2.setName("label2");
final JLabel label3 = new JLabel("label3");
label3.setName("label3");

MouseListener mouseListener = new MouseAdapter() {

  @Override
  public void mouseExited(MouseEvent e) {
    // you can check references
    if(e.getSource() == label1) {
      System.out.println("exited " + label1.getName());
    } else if (e.getSource() == label2) {
      System.out.println("exited " + label2.getName());
    } else if (e.getSource() == label3) {
      System.out.println("exited " + label3.getName());
    }
  }

  @Override
  public void mouseEntered(MouseEvent e) {
    String name = ((JComponent)e.getSource()).getName();
    // or you can check name of component
    switch (name) {
      case "label1":
      case "label2":
      case "label3":
        System.out.println("entered " + name);
        break;
    }
  }
};
for (JLabel l : Arrays.asList(label1, label2, label3)) {
  l.addMouseListener(mouseListener);
}
Ilya Bystrov
  • 2,902
  • 2
  • 14
  • 21
0

Note that labels need to be opaque in order to change their bg color.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;


public class CrazyLabels extends JFrame {

    public CrazyLabels() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
        JPanel content = new JPanel();
        add(content);
        content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));        

        MouseAdapter listener = new MouseAdapter() {

            @Override
            public void mouseEntered(MouseEvent e) {
                JLabel label = (JLabel)e.getSource();
                label.setBackground(Color.red);
            }

            @Override
            public void mouseExited(MouseEvent e) {
                JLabel label = (JLabel)e.getSource();
                label.setBackground(UIManager.getColor("Label.background"));
            }

        };

        for (int i = 0; i < 5; i++) {
            JLabel label = new MyLabel(listener);
            label.setText("---- label ----");
            content.add(label);
        }

        pack();
        setLocationRelativeTo(null);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                new CrazyLabels().setVisible(true);
            }
        });
    }

    private static class MyLabel extends JLabel {
        public MyLabel(MouseListener listener) {
            setOpaque(true);
            addMouseListener(listener);
        }
    }
}

In this example a single listener is used to enforce behavior in all labels.

Community
  • 1
  • 1
predi
  • 5,528
  • 32
  • 60