【发布时间】:2014-02-25 14:33:44
【问题描述】:
我创建了一个按钮,它应该运行一段代码来分析用户在文本字段中输入的文本。代码工作正常,但仅按“分析”按钮时我无法使代码工作,相反,当按下重置按钮时它仍然可以工作,我尝试添加 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());
} }};
任何帮助将不胜感激!
【问题讨论】:
-
this上的actionPerformed方法是什么? -
@NeplatnyUdaj 我希望该方法是一段以“String[] 数组”开头的代码,我希望在单击分析按钮时执行该代码?
-
我明白这一点。但是这段代码
resetButton.addActionListener(this);意味着您正在创建按钮的对象也实现了 ActionListener 因此必须有另一个actionPerformed您没有显示。代码中的动作监听器是一个匿名类,仅用于 countButton。 -
iv 解决了这个问题。谢谢
-
我很困惑。另一个 actionPerformed 中的内容是什么?还是这段代码处于非工作状态?