Java 使用JFileChooser上载文件时如何将文件传递到另一个类

Java 使用JFileChooser上载文件时如何将文件传递到另一个类,java,swing,jfilechooser,Java,Swing,Jfilechooser,我试图从JFileChooser中获取一个文件,然后将其传递到我的TextStatistics类中。我似乎无法保持对该文件的引用。。。任何帮助都将不胜感激 谢谢 ProcessText.java: public class ProcessText extends JPanel implements ActionListener { static private final String newline = "\n"; JButton openButton; JButton calculate;

我试图从JFileChooser中获取一个文件,然后将其传递到我的TextStatistics类中。我似乎无法保持对该文件的引用。。。任何帮助都将不胜感激

谢谢


ProcessText.java:

public class ProcessText extends JPanel implements ActionListener {
static private final String newline = "\n";
JButton openButton;
JButton calculate;
JTextArea log;
JFileChooser fc;

public ProcessText() {
    super(new BorderLayout());

    log = new JTextArea(5, 20);
    log.setMargin(new Insets(5, 5, 5, 5));
    log.setEditable(false);
    JScrollPane logScrollPane = new JScrollPane(log);


    JPanel buttonPanel = new JPanel(); // use FlowLayout
    buttonPanel.add(openButton);
    buttonPanel.add(calculate);

    // Add the buttons and the log to this panel.
    add(buttonPanel, BorderLayout.PAGE_START);
    add(logScrollPane, BorderLayout.CENTER);
}

public void actionPerformed(ActionEvent e) {
    File file = null;
    TextStatistics stat = null;

    if (e.getSource() == openButton) {
        int returnVal = fc.showOpenDialog(ProcessText.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            file = fc.getSelectedFile();
            stat = new TextStatistics(file);
        }
    }
    if (e.getSource() == calculate) {

        log.append(stat.toString());
    }

}

/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
    java.net.URL imgURL = ProcessText.class.getResource(path);
    if (imgURL != null) {
        return new ImageIcon(imgURL);
    } else {
        System.err.println("Couldn't find file: " + path);
        return null;
    }
}


private static void createAndShowGUI() {
    // Create and set up the window.
    JFrame frame = new JFrame("FileChooserDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Add content to the window.
    frame.add(new ProcessText());

    // Display the window.
    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    // Schedule a job for the event dispatch thread:
    // creating and showing this application's GUI.
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            // Turn off metal's use of bold fonts
            UIManager.put("swing.boldMetal", Boolean.FALSE);
            createAndShowGUI();
        }
    });
}
}

TextStatistics.java

public class TextStatistics implements TextStatisticsInterface {

public Scanner fileScan;

public int[] countLetters = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // gives      the starting values for count of each letter.
                            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; //initial amount of each letter. countLetters[0] corresponds to 'a'
                                                                //countLetters[1] to 'b' and so on.
public int[] length = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  //keeps word frequency lengths
                        0, 0, 0, 0, 0, 0, 0 };      
int lineCount = 0;  //keeps track of lines
int wordCount = 0;  //keeps track of words
int charCount = 0;  //keeps track of characters
double avg = 0;
double avgFinal = 0; //average word length
String strLine = "";
String largestWord;
File file;                                      
ArrayList<Integer> line; //line with longest word length

/**
 * reads in one file at a time and one line at a time to determine the
 * statistics described above.
 * 
 * @author Ryleigh More
 */

public TextStatistics(File file) {
    Scanner scan;
    try {
        scan = new Scanner(file);

        this.file = file;
        line = new ArrayList<Integer>();
        int largestIndex = 0;
        while (scan.hasNextLine()) {

            strLine = scan.nextLine().toLowerCase();
            lineCount++;
            charCount += strLine.length() + 1;
            StringTokenizer tokenizer = new StringTokenizer(strLine,
                    " , .;:'\"&!?-_\n\t12345678910[]{}()@#$%^*/+-");
            for (int i = 0; i < strLine.length(); i++) {
                char theLetter = strLine.charAt(i);

                if (theLetter >= 'a' && theLetter <= 'z')
                    countLetters[theLetter - 'a']++;

                while (tokenizer.hasMoreTokens()) {
                    String theWord = tokenizer.nextToken();
                    int currentWordLength = theWord.length();

                    if (currentWordLength > largestIndex) {

                        largestWord = theWord;
                        largestIndex = currentWordLength;
                        line.clear();
                    }

                    if (largestWord.equals(theWord)) {

                        line.add(lineCount);
                    }

                    if (currentWordLength < 23 && currentWordLength > 0) {
                        length[currentWordLength]++;
                    }

                    wordCount++;
                }

            }
        }
        for (int j = 1; j < length.length; j++)
            avg += (length[j] * j);

        avgFinal = avg / wordCount;
        scan.close();
    } catch (FileNotFoundException e) {
        System.out.println(file + " does not exist");
    }
}

/**
 * puts all the statistics in a String for printing by the ProcessText
 * class.
 * 
 * @return s
 * @author Ryleigh Moore
 */

public String toString() {
    DecimalFormat two = new DecimalFormat("#0.00");
    String s = "Statistics for " + file + "\n"
            + "======================================================\n"
            + lineCount + " Lines\n" + wordCount + " Words\n" + charCount
            + " Characters\n" + "-----------------------------------------"
            + "\na= " + countLetters[0] + "\t n= " + countLetters[13]
            + "\nb= " + countLetters[1] + "\t o= " + countLetters[14]
            + "\nc= " + countLetters[2] + "\t p= " + countLetters[15]
            + "\nd= " + countLetters[3] + "\t q= " + countLetters[16]
            + "\ne= " + countLetters[4] + "\t r= " + countLetters[17]
            + "\nf= " + countLetters[5] + "\t s= " + countLetters[18]
            + "\ng= " + countLetters[6] + "\t t= " + countLetters[19]
            + "\nh= " + countLetters[7] + "\t u= " + countLetters[20]
            + "\ni= " + countLetters[8] + "\t v= " + countLetters[21]
            + "\nj= " + countLetters[9] + "\t w= " + countLetters[22]
            + "\nk= " + countLetters[10] + "\t x= " + countLetters[23]
            + "\nl= " + countLetters[11] + "\t y= " + countLetters[24]
            + "\nm= " + countLetters[12] + "\t z: " + countLetters[25]
            + "\n-----------------------------------------"
            + "\n   Length      Frequency" + "\n   -------     ---------";

    for (int q = 1; q < length.length; q++) {
        if (length[q] > 0)
            s += "\n\t" + q + " =\t" + length[q];
    }

    s += "\nThe average word length = " + two.format(avgFinal)
            + "\nThe longest word is '" + largestWord + "' and is on line "
            + line
            + "\n======================================================";

    return s;

}
public类TextStatistics实现TextStatistics接口{
公共扫描仪文件扫描;
public int[]countLetters={0,0,0,0,0,0,0,0,0,0,0,0,0,//给出每个字母的计数起始值。
0,0,0,0,0,0,0,0,0,0,0};//每个字母的初始数量。countLetters[0]对应于“a”
//将字母[1]倒计时到“b”,以此类推。
public int[]length={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,//保留字频长度
0, 0, 0, 0, 0, 0, 0 };      
int lineCount=0;//跟踪行
int wordCount=0;//跟踪单词
int charCount=0;//跟踪字符
双平均值=0;
double avgFinal=0;//平均字长
字符串strLine=“”;
字符串最大的单词;
文件;
ArrayList行;//字长最长的行
/**
*一次读取一个文件,一次读取一行,以确定
*上述统计数字。
* 
*@作者Ryleigh More
*/
公共文本统计(文件){
扫描仪扫描;
试一试{
扫描=新扫描仪(文件);
this.file=文件;
line=新的ArrayList();
int-largestIndex=0;
while(scan.hasNextLine()){
strLine=scan.nextLine().toLowerCase();
lineCount++;
charCount+=strLine.length()+1;
StringTokenizer tokenizer=新的StringTokenizer(strLine,
“,.;:“\”&!?-\un\t12345678910[]{}()@$%^*/+-”;
对于(int i=0;i='a'&字母最大索引(&T){
最大的单词=单词;
最大索引=当前字长;
line.clear();
}
如果(最大的单词等于(单词)){
行。添加(行计数);
}
如果(currentWordLength<23&¤tWordLength>0){
长度[currentWordLength]+;
}
字数++;
}
}
}
对于(int j=1;j0)
s+=“\n\t”+q+=\t”+length[q];
}
s+=“\n平均字长=“+2.format(avgFinal)
+“\n最长的单词是”“+largestWord+”,并且处于联机状态”
+线
+“\n===================================================================”;
返回s;
}
问题是,当你按下
openButton
时,它会创建新的
TextStatistics
,但就是这样。它不会将文本附加到
JTextArea
。你只需按下
calculate
。因此当按下
openButton
时,会创建本地
TextStatistics
,然后我就什么都没有了当按下
calculate
时,日志试图附加一个空的
TextStatistics


因此,您可以将
TextStatistics stat
附加到
if内部的
log
(e.getSource()==openButton){
或使
TextStatistics
成为一个全局类成员,它将在按钮按下之间保持。因此,当按下
openButton
时,
TextStatistics stat
将保持按下
calculate
按钮。

每次运行
actionPerformed
时,它都会生成一个新变量
stat
,并设置但实际上,您希望对
actionPerformed
的两个不同调用使用同一个变量副本

我建议将声明
TextStatistics stat=null;
移出<
public void actionPerformed(ActionEvent e) {
    File file = null;
    TextStatistics stat = null;

    if (e.getSource() == openButton) {
        int returnVal = fc.showOpenDialog(ProcessText.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            file = fc.getSelectedFile();
            stat = new TextStatistics(file);
        }
    }
    if (e.getSource() == calculate) {

        log.append(stat.toString());
    }
}