0

I have created some dynamical JLabels and i have added MouseLister to each of them. Now the problem is how can i detect which JLabel I have Clicked? Here's my code.

    int c1=40;
    setLayout(null);
    jPanel1.setSize(new Dimension(500, 200));
    jPanel1.setLayout(new GridLayout(4, 10));
        JLabel[] jl = new JLabel[c1];
    for(int i=c1-1; i>=0; i--){
        jl[i] = new JLabel();
        //jl.setText("O");
        jl[i].setPreferredSize(new Dimension(20,20));
        jl[i].setIcon(new ImageIcon(NewJFrame.class.getResource("booked.png")));
        jl[i].setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        jPanel1.add(jl[i]);
        jl[i].addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent me){

            }
    });
    }
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Arpan
  • 596
  • 2
  • 10
  • 29
  • 1
    1) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). Layouts can be added to, 2) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). – Andrew Thompson Jun 30 '15 at 05:56
  • 1
    Consider using multiple `JButton` components with an `ActionListener` instead of the label/mouse listener combo. This is better for the user, since they can use mouse **or** keyboard to operate them. – Andrew Thompson Jun 30 '15 at 05:57

1 Answers1

3

for each JLabel you are adding a new/seperate MouseAdapter Object

 jl[i].addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent me){

        }
});

So calling me.getComponent() inside the mousePressed event should return you the Label Object

jl[i].addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent me){
                   //Better to check if its returning JLabel obejct using instance of
                   JLabel c = (JLabel) me.getComponent();
            }
    });
Sarfaraz Khan
  • 2,166
  • 2
  • 14
  • 29
  • But how can i uniquely identify that JLabel ? @Sarfaraz Khan – Arpan Jun 30 '15 at 05:52
  • OK i got the solution i added name for each JLabel and using your me.getComponent().getName() i can identify each JLabel. Thanks for the help. – Arpan Jun 30 '15 at 05:55