调用在ActionListener中获取参数的方法

时间:2016-07-28 12:36:16

标签: java parameters actionlistener

我在尝试调用实现actionListener的类中的方法时遇到了问题。被调用的方法DataCompiler需要使用wordCountWhole类中返回的整数wordCount。问题是我无法将所需参数传递给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类的代码:

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

1 个答案:

答案 0 :(得分:1)

您没有在那里添加参数,因为您已经使接口合同无效。

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

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类/侦听器代码中使用Integer.parseInt(textInput.getText().trim())而不使用构造函数。否则,您在添加处理程序时始终会获得数字值,这将是一个空字符串并抛出错误,因为文本区域中没有数字。

此外,wc.miner();返回一个值,但是自己调用它而不将其分配给一个数字只会抛弃该返回值。