我正在使用Java中的Netbeans IDE。如何在單擊jPanel(Java)時調用函數?
我有一個JPanel的一種形式。 每個JPanel都有一個gridLayout 3x3,並且在每個位置都有一個表示數字[0,1,2,3,4,5,6,7,8]的圖像(該圖像使用自定義類創建,而不僅僅是擬合在實驗室中的圖像)。
我希望能夠在面板交換兩幅圖像,當用戶點擊他們(首次點擊:不採取行動,第二次點擊:開關安裝在JPanel組件中的兩個圖像)。
我已經創建了一個功能exchangeComponents和用測試碼(如:
exchangeComponents (0,8,jPanel1)
它交換正確地)(位於位置1(第一行,第一列中的圖像,並在情況2第3行,第3列) 。
的功能的creted如下:
public void exchangeComponents(int component1,int component2,JPanel jpanel){
try{
Component aux1 = jpanel.getComponent(component1);
Point aux1Loc = aux1.getLocation();
Component aux2 = jpanel.getComponent(component2);
Point aux2Loc = aux2.getLocation();
aux1.setLocation(aux2Loc);
aux2.setLocation(aux1Loc);
}
catch (java.lang.ArrayIndexOutOfBoundsException ex){ /* error! bad input to the function*/
System.exit(1);
}
}
我想我neeed爲具有調用函數exchangeComponents()的事件時,用戶C舔jPanel1上的圖像之一,但我應該怎麼做?以及如何檢查用戶選擇了哪些組件(圖像)? 我只知道,當我創建一個按鈕,如果在創建上有一個點擊(從IDE)像
private void button1ActionPerformed(java.awt.event.ActionEvent evt) {
// some code..
}
一個事件,我填寫代碼被執行。
非常感謝您提供任何提示。
謝謝。這很清楚..但與img1.addMouseListener(this);我通過表單本身,它說「錯誤:預期的MouseListener」。所以呢? – dragonmnl 2012-04-02 13:13:24
好吧,我做了它(做了一個類getComponent實現MouseListener)並使用img1.addMouseListener(新的ComponentListener())。現在的問題是..我爲每個組件添加了一個偵聽器,但是當我點擊任何組件時(圖片),事件根本沒有被觸發 – dragonmnl 2012-04-02 14:15:08
對不起,我認爲我沒有說清楚,但是你的班級需要實現MouseListener,然後您需要將偵聽器添加到正在切換的每個組件。 @dragonml – DankMemes 2012-04-03 20:49:52