我正在尝试从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 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) {或使TextStatistics stats成为全局类成员,该成员将在两次按键之间保持不变。因此,当按下openButton时,TextStatisitcs stat将持续按下calculate按钮。

09-27 17:01