【问题标题】:Java Applet button [closed]Java Applet 按钮 [关闭]
【发布时间】: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 中的内容是什么?还是这段代码处于非工作状态?

标签: java swing applet


【解决方案1】:

您在两次按下按钮时都调用了相同的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();
   }
}

【讨论】:

  • 效果很好!非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-24
  • 1970-01-01
  • 2021-10-09
相关资源
最近更新 更多