2

I have a JLabel[10] and I want to detect which label has been clicked and print which label of the label that has been clicked.

  1. I created a JLabel array of 10.
  2. Wrote a for loop to place an Image to every position of the label.
  3. Added a MouseListener to check which label has been clicked.

The problem is I can't do this to get the source of my jLabelArr. The program will ask me to change my it to final.

   if(e.getSource() == jLabelArr[i]) 

Full code

import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class JavaLabels extends JFrame {

private JLabel[] jLabelArr;
private JPanel jLabelPanel = new JPanel();

    public JavaLabels() {
        setLayout(new FlowLayout());
        jLabelArr = new JLabel[10];
        for(int i =0; i < 10; i++) {

            jLabelArr[i] = new JLabel(new ImageIcon("resources/image"));
            jLabelPanel.add(jLabelArr[i]); 

            jLabelArr[i].addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if(e.getSource() == jLabelArr[i]) {
                        System.out.println("Label" + i + "was clicked");
                    }
                }
            });
        }
        add(jLabelPanel);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        pack();
        setSize(400,600);
        setLocationRelativeTo(null);
        setVisible(true);
    }
    public static void main(String[] args) {
        new JavaLabels();
    }
}
Community
  • 1
  • 1
user3820292
  • 310
  • 3
  • 19
  • 1
    have you considered using a jbutton instead of a jlabel? also, i think you can get around your immediate problem by doing something like `final JLabel j = jLabelArr[i];` – clearlyspam23 Jul 11 '14 at 04:17
  • Is there any difference? – user3820292 Jul 11 '14 at 04:19
  • put the code in `mouseCLicked` event in another method and call that method in `mouseClickedEvent` or implement MouseListener to JavaLabels and add current instance of `Javalabels` to objects of `JLabel` array using `this` – A Stranger Jul 11 '14 at 04:19
  • 2
    why not create a local final variable inside your loop. like `final int labelIndex=i;` and use it instead of i inside mouseClicked – Shailesh Aswal Jul 11 '14 at 04:25
  • Final local variable can be accessed inside inner class, so you will be having the compilation issue for "int i". Moreover JLabel is used to dispay where as Jbutton is used for action to be performed. Why do you want to perform same action on clicking 10 JLabels? – Kishore Jul 11 '14 at 04:26
  • @Shail016 That should be an answer – Paul Samsotha Jul 11 '14 at 04:28
  • @peeskillet let him take clue and make things work for him. And regarding buttons instead of labels, let the op use what he wants, he might be exploring swing components. – Shailesh Aswal Jul 11 '14 at 04:30
  • @Shail016 yes you are right. I am exploring swing components – user3820292 Jul 11 '14 at 04:31
  • @user3820292: As to why you need to declare the variable as __final__, hopefully this [post](http://stackoverflow.com/a/13209458/1057230), might be able to explain a bit in that direction :-) – nIcE cOw Jul 11 '14 at 05:50
  • 3
    @clearlyspam23 Yes, and when they swap the `JLabel` for a (possibly undecorated) `JButton` they can change the `MouseListener` for an `ActionLListener` and it will respond to mouse *or keyboard* input. See [this Chess game GUI](http://stackoverflow.com/q/21142686/418556) that uses this approach. Also a [second example](http://stackoverflow.com/a/10862262/418556) that mixes labels (which aren't intended to be focused or clicked on) with buttons (that are). – Andrew Thompson Jul 11 '14 at 06:14

2 Answers2

4

For what you wanted there's nothing more than create a final int variable that will equal to the position of the for cycle

import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class JavaLabels extends JFrame {

private JLabel[] jLabelArr;
private JPanel jLabelPanel = new JPanel();

    public JavaLabels() {
        setLayout(new FlowLayout());
        jLabelArr = new JLabel[10];
        for(int i =0; i < 10; i++) {

            jLabelArr[i] = new JLabel(new ImageIcon("resources/image"));
            jLabelPanel.add(jLabelArr[i]); 
            final int p = i;
            jLabelArr[i].addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    System.out.println("Label" + p + "was clicked");
                }
            });
        }
        add(jLabelPanel);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        pack();
        setSize(400,600);
        setLocationRelativeTo(null);
        setVisible(true);
    }
    public static void main(String[] args) {
        new JavaLabels().setVisible(true);
    }
}

-> if(e.getSource() == jLabelArr[i]) is not needed in this case

Jonathan Solorzano
  • 6,812
  • 20
  • 70
  • 131
2

1

public class JavaLabels extends JFrame {

    private JLabel[] jLabelArr;
    private JPanel jLabelPanel = new JPanel();

    public JavaLabels() {
        setLayout(new FlowLayout());
        jLabelArr = new JLabel[10];
        for (int i = 0; i < 10; i++) {

            jLabelArr[i] = new JLabel(new ImageIcon("resources/image"));
            jLabelPanel.add(jLabelArr[i]);

            jLabelArr[i].addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    onMouseClicked(e);
                }
            });
        }
        add(jLabelPanel);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        pack();
        setSize(400, 600);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void onMouseClicked(MouseEvent e) {
        for (int i = 0; i < 10; i++)
            if (e.getSource() == jLabelArr[i]) {
                System.out.println("Label" + i + "was clicked");
            }
    }

    public static void main(String[] args) {
        new JavaLabels();
    }
}

2

Implement MouseListener to JavaLabels class and jLabelArr[i].addMouseListener(this);

nIcE cOw
  • 24,468
  • 7
  • 50
  • 143
A Stranger
  • 551
  • 2
  • 11