2014-02-25 49 views
-3

我已經創建了一個按鈕,它應該運行一段代碼,用於分析用戶輸入到文本字段中的文本。代碼工作正常,但我不能讓代碼工作時按'分析'按鈕,而是它仍然按按鈕時重置按鈕,我試圖添加ActionListener但它似乎仍然工作?Java Applet按鈕

/* Creating Analyze and Reset buttons */ 

     JButton countButton = new JButton("Analyze"); 
     //countButton.addActionListener(this); 
     south.add(countButton); 

     JButton resetButton = new JButton("Reset"); 
     resetButton.addActionListener(this); 
     south.add(resetButton); 

/Text analysis start 
    countButton.addActionListener(new ActionListener() { 
public void actionPerformed(java.awt.event.ActionEvent e) { 
    String[] array = textInput.getText().split(" "); 
    int maxWordLength = 0; 
    int wordLength = 0; 
    for (int i = 0; i < array.length; i++) { 
     array[i] = array[i].replaceAll("[^a-zA-Z]", ""); 
     wordLength = array[i].length(); 
     if (wordLength > maxWordLength) { 
      maxWordLength = wordLength; 
     } 
    } 
    int[] intArray = new int[maxWordLength + 1]; 
for (int i = 0; i < array.length; i++) { 
    intArray[array[i].length()]++; 
} 
StringWriter sw = new StringWriter(); 
PrintWriter out = new PrintWriter(sw); 
out.print("<html>"); 
for (int i = 1; i < intArray.length; i++) { 
    out.printf("%d word(s) of length %d<br>", intArray[i], i); 
} 
out.print("</html>"); 
wordCountLabel.setText(sw.toString()); 

} }};

任何幫助將不勝感激!

+1

什麼是'''this''' actionPerformed方法? – NeplatnyUdaj

+0

@NeplatnyUdaj我想的方法是片的起始「String []數組」代碼,我想在單擊分析按鈕時要執行的代碼? – abdul

+0

我明白這一點。但是這段代碼'''resetButton.addActionListener(this);'''意味着你創建按鈕的對象也實現了ActionListener,所以必須有另一個'''actionPerformed'',而你沒有顯示。代碼中的動作偵聽器是一個僅用於countButton的匿名類。 – NeplatnyUdaj

回答

2

對於兩個按鈕按鈕,您都調用相同的ActionListener,因此您需要區分actionPerformed()方法中要執行的操作。使用getActionCommand()此:

public void actionPerformed(java.awt.event.ActionEvent e) { 
    String command = e.getActionCommand(); 

    if (command.equals("Analyze")) { 
     // doAnalyze(); 
    } else if (command.equals("Reset")) { 
     // doReset(); 
    } 
} 
+0

這很好用!非常感謝 – abdul