2015-06-30 57 views
0

我已經創建了一些動態的JLabels,並且我已經爲它們中的每一個添加了MouseLister。現在的問題是我如何檢測我點擊了哪個JLabel? 這是我的代碼。多個JLabel上的鼠標Listern

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

1 )Java GUI必須在不同的語言環境中使用不同的PLAF來處理不同的操作系統,屏幕大小,屏幕分辨率等。因此,它們不利於像素的完美佈局。請使用佈局管理器或[它們的組合](http://stackoverflow.com/a/5630271/418556)以及[white space]的佈局填充和邊框(http://stackoverflow.com/a/17874718/ 418556)。可以添加布局,2)爲了更快地獲得更好的幫助,請發佈[MCVE](http://stackoverflow.com/help/mcve)(最小完整可驗證示例)或[SSCCE](http://www.sscce。 org /)(簡短,獨立,正確的例子)。 –

+1

考慮將多個JButton組件與「ActionListener」組合使用,而不是標籤/鼠標偵聽器組合。這對用戶來說更好,因爲他們可以使用鼠標**或**鍵盤來操作它們。 –

回答

3

每個JLabel的要添加新/獨立MouseAdapter對象

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

     } 
}); 

所以調用me.getComponent()的事件的mousePressed裏面應該回到你的標籤對象

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(); 
      } 
    }); 
+0

但是,我如何唯一標識JLabel? @Sarfaraz Khan – Arpan

+0

好吧,我得到了解決方案,我爲每個JLabel添加了名稱,並使用您的me.getComponent()。getName()我可以識別每個JLabel。謝謝您的幫助。 – Arpan