多个JLabel上的鼠标Listern

时间:2015-06-30 05:40:28

标签: java swing jlabel mouselistener

我创建了一些动态JLabels,并为每个人添加了MouseLister。现在的问题是如何才能检测到哪个JLabel我点击了? 这是我的代码。

    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){

            }
    });
    }

1 个答案:

答案 0 :(得分:3)

为每个JLabel添加一个新的/单独的MouseAdapter对象

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

        }
});

因此,在mousePressed事件中调用me.getComponent()应该返回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();
            }
    });