2013-01-22 52 views
0

我正在編碼圖像益智遊戲,代碼的一部分是比較用戶選擇的部分片段的正確圖像。通過setName()比較組件。

每個圖像片段已作爲ImageIcon添加到JButton中。

需要一個標識符來區分每個圖像塊並進行比較。

我爲每個JButton創建一個setName()作爲標識符。

比較在用戶從原始3x3網格中拖拽拼圖後釋放鼠標時開始,在這個網格中將混洗的部分放到其他3x網格進行匹配。

我有問題,從比較if聲明中刪除錯誤。

我從這個SO線程比較主意 - link

private JButton[] button = new JButton[9]; 
    private JButton[] waa = new JButton[9]; 

    private String id; 
    private int cc; 
    private String id2; 
    private int cc2; 

    // setName for each of the 9 buttons in the original 3x3 grid being created 
    // which stores the shuffled puzzle pieces 
    for(int a=0; a<9; a++){ 
     button[a] = new JButton(new ImageIcon()); 
     id += Integer.toString(++cc); 
     button[a].setName(id); 
    } 

    // setName for each of the 9 buttons in the other 3x3 grid 
    // where the images will be dragged to by the user 
     for(int b=0; b<9; b++){ 
     waa[b] = new JButton(); 
     id2 += Integer.toString(++cc2); 
     waa[b].setName(id2); 
    } 

    // check if puzzle pieces are matched in the correct place 
    // compare name of original 'button' array button with the name of 'waa' array buttons 
     button[a].addMouseListener(new MouseAdapter(){ 

      public void mouseReleased(MouseEvent m){ 
       if(m.getbutton().getName().equals (waa.getName())){ 

        } 
        else{ 
         JOptionPane.showMessageDialog(null,"Wrong! Try Again."); 
        } 
      } 
     } 

回答

3

在你mouseReleased事件m.getButton()將返回被點擊鼠標按鈕。你會想要做更多像這樣的東西,將讓你更接近:

if (m.getComponent().getName().equals(waa.getName())) { 

m.getComponent()返回Component對象(你JButton),該事件從被解僱。從那裏您可以與您使用的getName方法進行比較。

還有一個問題,因爲你的waa變量是一個數組。我不確定您想如何比較它們,無論是通過數組運行並確保索引和名稱匹配,但這是您需要研究的另一個問題。

+1

如果您不關心是否鼠標事件發生在按鈕上,MouseEvent包含一個getComponent方法,該方法應允許放棄演員(至少您確定您想要)。就我個人而言,我也正在檢查以確保getName沒有返回空值 – MadProgrammer

+2

其實,當我想到它時,爲什麼我們在按鈕上使用鼠標監聽器? – MadProgrammer

+0

關於'getComponent'的好處是,我更新了代碼。鼠標監聽器也是不必要的,它可以通過'addActionListener'完成。在上面的代碼中顯然有一些問題,但希望這會讓OP開始朝着正確的方向發展。 –

3

JButton使用ActionListener觸發通知回到您的程序以指示它何時被觸發。這允許按鈕響應不同類型的事件,包括鼠標,鍵盤和程序觸發器。

作爲操作API的一部分,您可以爲每個按鈕提供操作命令。見JButton#setActionCommand

基本上你會在simular方式到您的鼠標監聽它集成...

public void actio Performed(ActionEvent evt) { 
    if (command.equals(evt.getActionCommand()) {...} 
} 

根據您的要求,它甚至可能會更易於使用的Action API

您的問題實際上是waa是一個數組,因此它沒有getName方法。我也不清楚爲什麼你有兩個按鈕陣列?

+0

哦,第9個按鈕陣列用於顯示存儲爲ImageIcons的9個混洗件。第9個按鈕的第二個數組供用戶將其拖動到。 – iridescent

+2

@iridescent:聽起來好像你使用JButtons作爲真正的按鈕,而是作爲存儲庫來保存JLabel。爲什麼要使用JButtons呢?爲什麼不簡單地創建並使用一組JLabel來保存ImageIcons? –

+0

如果您願意,也可以使用拖放來移動圖標。 1+瘋狂的方式。 –