Question

I am trying to take in a file from a JFileChooser that I can then pass into my TextStatistics class. I can't seem to keep reference to the file... Any help would be greatly appreciated.

Thanks!


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;

}
Était-ce utile?

La solution

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

The thing is, when you press the openButton, it creates the new TextStatisics but that's it. It doesn't append the text the the JTextArea. You only do that with the press of calculate. So when openButton is pressed, the local TextStatistics is created, then nothing is don't with it, so it's tossed out. When calculate is pressed, the log tries to append a null TextStatistics.

So you can either append the TextStatistics stat to the log inside of the if (e.getSource() == openButton) { or make TextStatistics stats a global class member that will persist between button presses. So when openButton is pressed, TextStatisitcs stat will persist to a calculate button press.

Autres conseils

Every time actionPerformed runs, it makes a new variable stat and sets it to null. But you actually want two different calls to actionPerformed to use the same copy of the variable.

I would recommend moving the declaration TextStatistics stat = null; out of actionPerformed and putting it at the top of the class, before all the methods, so that stat becomes a field of the class. That way, its value will survive from one actionPerformed call to the next.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top