2011-03-10 82 views
13

我想用JLabel替換JButton,並且希望我的代碼在單擊JLabel時執行某些操作。我可以向JLabel添加一個動作偵聽器嗎?

當我有一個JButton我用動作監聽器來處理按鈕點擊:

myButton.addActionListener(new clicksListener(arg1,this)) 

當我更換myButton通過myLabel我在Eclipse以下錯誤信息:

的方法 addActionListener(ChipsListener)爲 undefined爲類型JLabel

但我知道應該可以將附加的Click處理程序附加到JLabel。有人知道如何做到這一點嗎?

回答

23

MouseListener添加到JLabel

因爲JLabelComponent,您可以添加MouseListener s到它。使用該界面並在您的MouseListener上寫上mouseClicked事件來處理點擊。

+0

我不明白你的邏輯。你的意思是所有'Component'都可以添加'MouseListener'(任何引用)?什麼樣的小部件可以添加'ActionListener'? – Tony 2014-12-31 10:55:56

+2

是的,'addMouseListener()'方法在'Component'上定義。當鼠標進入或退出組件時,或者在組件內按下按鈕或在組件內按下按鈕後,此類會生成MouseEvent對象。任何擴展Component的類都可以有任意數量的監聽這些事件的MouseListener引用。 addActionListener()'在'AbstractButton'上定義,並在按下按鈕時生成'ActionEvent'對象。由於'JLabel'沒有擴展'AbstractButton',它不會生成'ActionEvent'對象。試試'JButton'。 – 2014-12-31 20:23:24

11

更簡單的方法是使用JButton,因爲它已通過使用ActionListener支持此功能。

您可以將JButton看起來像一個JL​​abel使用:

button.setBorderPainted(false); 

這種方法是當你要處理的鼠標點擊,因爲一個ActionEvent是保證生成的,而作爲的mouseClicked事件中使用時,可能不會在所有情況下生成MouseListener,這可能會混淆用戶。

+0

恐怕它更復雜,請參閱http://stackoverflow.com/questions/3025320/draw-a-jbutton-to-look-like-a-jlabel-or-at-least-without-the-button-edge – xmedeko 2012-10-11 14:18:08

+0

什麼情況下不會生成mouseClicked事件? – Buffalo 2013-04-03 07:37:55

+1

@Buffalo,當在同一點處生成mousePressed和mouseReleased事件時,會生成mouseClicked事件。因此,如果用戶在這兩個事件之間將鼠標移動一個像素,則不會獲得mouseClicked。 – camickr 2013-04-03 15:28:03

7
/*add a mouselistener instead and listen to mouse clicks*/ 
    jlable.addMouseListener(new MouseAdapter() { 
       @Override 
       public void mouseClicked(MouseEvent e) { 
        System.out.println("Yay you clicked me"); 
       } 

      }); 
+0

總是嘗試提供一些解釋,除了發佈代碼。同時它可能對你來說顯然微不足道,對其他人來說可能很難理解。 – 2016-01-05 16:15:19

相關問題