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

时间:2014-03-25 02:14:13

标签: java swing jfilechooser

我正在尝试从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;

}

2 个答案:

答案 0 :(得分:2)

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());
    }
}

问题是,当您按下openButton时,它会创建新的TextStatisics,但就是。它不会将文本附加到JTextArea。你只有按calculate才能这样做。因此,当按下openButton时,会创建本地TextStatistics,然后没有任何内容与它一起,所以它被抛出。按下calculate时,日志会尝试附加空TextStatistics

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

答案 1 :(得分:0)

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

我建议在所有方法之前将声明TextStatistics stat = null;移出actionPerformed并将其放在类的顶部,以便stat成为类的一个字段。这样,它的值将从一个actionPerformed调用到下一个调用。