在 ActionListener 中调用采用参数的方法

Calling a Method That Takes a Parameter Within ActionListener

我在尝试调用实现 actionListener 的 class 中的方法时遇到问题。被调用的方法 DataCompiler 需要使用整数 wordCountWhole,它在 wordCount class 中返回。问题是我无法将所需参数传递给 actionListener method.

 import javax.swing.*;
 import java.awt.*;
 import java.awt.List;
 import java.awt.event.*;
 import java.beans.PropertyChangeListener;
 import java.text.BreakIterator;
 import java.util.*;
 import java.util.stream.IntStream;

 public class GUI extends JFrame {
     public JTextArea textInput;
     public JButton dataButton;
     public String str;

     public GUI() {
         super("Text Miner");
         pack();
         setLayout(null);

         dataButton = new JButton("View Data"); //Button to take user to data table
         dataButton.setSize(new Dimension(120, 50));
         dataButton.setLocation(5, 5);
         Handler event = new Handler(); //Adds an action listener to each button
         dataButton.addActionListener(event);
         add(dataButton);

         public class wordCount {
             public int miner() {
                 //This returns an integer called wordCountWhole
             }
         }

         public class Handler implements Action { //All the possible actions for when an action is observed

             public void action(ActionEvent event, int wordCountWhole) {

                 if (event.getSource() == graphButton) {
                     Graphs g = new Graphs();
                     g.Graphs();
                 } else if (event.getSource() == dataButton) {
                     DataCompiler dc = new DataCompiler();
                     dc.Data(wordCountWhole);
                 } else if (event.getSource() == enterButton) {
                     wordCount wc = new wordCount();
                     sentenceCount sc = new sentenceCount();
                     wc.miner();
                     sc.miner();
                 }
             }
         }
     }

这里是 DataCompiler 的代码 class:

public class DataCompiler{
    public void Data(int wordCountWhole){
        int m = wordCountWhole;
        System.out.println(m);
    }
}

您没有在此处添加参数,因为您已经使接口协定无效。

使用构造函数*(首先请参阅下面的注释)

public class Handler implements Action{ //All the possible actions for when an action is observed

    private int wordCountWhole;

    public Handler(int number) { this.wordCountWhole = number; } 

    @Override 
    public void actionPerformed(ActionEvent event) {

虽然,但并不完全清楚您为什么需要这个数字。您的 DataCompiler.Data 方法只打印传递给它的数字,并且该变量似乎来自您的代码中的任何地方,因为它没有传递给 ActionListener。

* 您应该在 Handler class / 侦听器代码中使用 Integer.parseInt(textInput.getText().trim()) 而不是使用构造函数。否则,当您添加处理程序时,您总是会得到数字值,这将是一个空字符串并抛出错误,因为文本区域中没有数字。

此外,wc.miner(); return 是一个值,但是单独调用它而不将其分配给数字只会丢弃 return 值。