airsoftFreak
airsoftFreak

Reputation: 1598

How do i add a mouseListener to a anonymous JLabel object?

Currently I'm using a for-loop to populate the JPanel with numbers from 1-31

So basically, What I want to do is if let say i click on number 1, it will do show

System.out.println(1);

Here's the code:

     public class MonthPanel extends JPanel implements MouseListener {

        public MonthPanel() {
            setLayout(new GridLayout(6,7));
            // Add headers
                // Use for-each loop.
                for (String header : headers) {
                  add(new JLabel(header));
                }

                for (int i = 1; i < 31; i++) {
                  add(new JLabel(String.valueOf(i)));
                }

            addMouseListener(this);
        }

    public void mouseClicked(MouseEvent e) {
            // What should i do in here to get a specific JLabel? 
               }
        }
}

Here's the picture

enter image description here

Upvotes: 0

Views: 2353

Answers (2)

Instead of adding like that you can do something like

for (String header : headers) {
      JLabel lbl = new JLabel(header);
      lbl.addMouseListener(add ur listner);
      add(lbl);
}

In the mouseClicked event you can get the JLabel and print its text as follows

public void mouseClicked(MouseEvent e) {
    System.out.println(((JLabel) e.getSource()).getText());
}

In your code if you implement the MouseListener interface you must override all the abstract method in that. Otherwise it will not compile

Upvotes: 2

Programmer
Programmer

Reputation: 453

Here's the solution

First you have to add mouselistener in label which should have mouse adapter in brackets its because you only want to use mouse click method.

Than add mouseClicked method in it .

and than add you code in mouseClicked method.

Example:

    JLabel l = new JLabel("label");
    l.addMouseListener(new MouseAdapter() {

        public void mouseClicked(MouseEvent e) {

            // Your Code Here

        }

    });
    add(l);

Upvotes: 3

Related Questions