2016-07-28 82 views
0

在嘗試調用實現actionListener的類中的方法時遇到問題。被調用的方法DataCompiler需要使用wordCount類中返回的整數wordCountWhole。問題是我無法將所需參數傳遞給actionListener method調用ActionListener中的參數的方法

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

你不存在添加參數,因爲你已經失效的接口的合同。

使用構造*(參見下面的註釋,第一)

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();返回一個值,但是調用它自己而不將它分配給一個數字只是拋出該返回值。

+0

非常感謝您的回覆!我遵循你的建議,一切似乎都很好,直到運行該程序,然後它會拋出一個錯誤,告訴我「構造函數GUI.Handler()未定義」,所以我不確定我做錯了什麼。我只用Java編寫了大約兩個月的編程,所以我仍然在處理它。你想讓我發佈修改後的代碼嗎? – MDP503

+0

我的答案的後半部分解釋說你不應該使用構造函數,因爲你不應該把整數傳遞給監聽器。 –

+0

也許我應該更好地解釋一下,我需要這個整數來做一些數據分析,而DataCompiler類將比較不同的值並將它們打印到屏幕上,而不僅僅是原始整數。如果沒有將這個整數傳遞給actionlistener,我無法調用DataCompiler方法。對不起〜 – MDP503