Java Applet按钮

时间:2014-02-25 14:33:45

标签: java swing applet

我创建了一个按钮,它应该运行一段代码,分析用户输入文本字段的文本。代码工作正常,但是只有通过分析'才能使代码工作。按钮,相反,当按下重置按钮时它仍然会这样做,我尝试添加ActionListener,但它似乎仍然无法正常工作?

/* 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 个答案:

答案 0 :(得分: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();
   }
}