2016-02-24 25 views
-1

根據用戶的決定,我有'n'個按鈕。每當我點擊按鈕,我想讓它給我點擊的次數。棘手的是我沒有給按鈕設置任何名字,用戶也沒有。所以我的問題是,如何使用e.getActionCommand()檢查'countAmount'是否爲1或更多?如何使用e.getActionCommand()從按鈕獲得點擊次數?

我真的被困在這個問題上,如果任何人都可以幫助這將是偉大的!這是我的計劃的一部分,任何幫助都會很棒!

private static int countAmount = 0; 

public Example() 
{ 
    str = JOptionPane.showInputDialog("What is the name of the new button?"); 
    JButton b18 = new JButton(str); 

    //The actionlistener stuff 
    countAmount++; 

    if (countAmount % 2 != 0) 
    { 
     System.out.println(e.getActionCommand() + "was clicked, count is even"); 
    } 
    else 
    { 
     System.out.println("The button was clicked, count is odd"); 
    } 

    if (countAmount.(e.getActionCommand) == 1) 
    { 
     System.out.println("This button has been clicked " + countAmount + " times); 
    } 
} 
+0

這不一定是'ActionListener'應該用於什麼。你應該使用'MouseListener'和'MouseEvent'。 – Zizouz212

+1

@ Zizouz212:不,我會使用一個ActionListener,如果他只是簡單地按鈕按計數。 –

+2

對於原始海報,如果您創建併發布了體面的[mcve],則會更好地服務。但爲了快速解決問題,可以考慮使用一個int數組或一個'HashMap '來保存所有按鈕的計數。 –

回答

2
  1. 把你的按鈕爲ArrayList<JButton>
  2. 按下按鈕時,不要擔心ActionCommand。
  3. 而是通過調用按鈕的ActionListener中的ActionEvent參數getSource()來獲得對實際按鈕本身的引用。
  4. 要找出哪個按鈕被按下,用for循環遍歷按鈕的ArrayList。
  5. 當你找到一個匹配,使用該按鈕的索引數組列表中增加一個ArrayList<Integer>
  6. 或者你可以簡單地創建一個HashMap<JButton, Integer>和簡單的增加與源JButton的鍵關聯的整數值。
  7. 如需更詳細的解答,請發佈真實有效的Minimal, Complete, and Verifiable example程序。
+0

如果我不知道它的名字,我將如何在arraylist中找到按鈕?因爲用戶正在寫這個名字。我將編輯更多的代碼,這樣纔有意義。 –

+0

@ D.Maximov:你只需使用簡單的for循環遍歷ArrayList即可。並且明白這個「名字」在這裏並不重要。而***參考***是。 –

+0

那麼,getSource()就像getActionCommand()一樣?有什麼不同? –