The program below reads a text file and lists the words alphabetically.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
// File : readwords/ReadWordsGUI.java
// Purpose: Read a file and display all words in it.
// Author : Fred Swartz
// Date : 2005-03-10
package readwords;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
class ReadWordsGUI extends JPanel {
//... Instance variables
JTextArea m_wordListTA = new JTextArea(25, 15);
JFileChooser m_fileChooser = new JFileChooser();
ArrayList<String> m_words = new ArrayList<String>();
//======================================================== constructor
ReadWordsGUI() {
JButton openButton = new JButton("Open");
//... Add listeners
openButton.addActionListener(new OpenAction());
//... Layout components
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.add(openButton);
this.add(new JScrollPane(m_wordListTA));
}
/////////////////////////////////////////////////// inner listener class
class OpenAction implements ActionListener {
public void actionPerformed(ActionEvent ae) {
int retval = m_fileChooser.showOpenDialog(ReadWordsGUI.this);
if (retval == JFileChooser.APPROVE_OPTION) {
File file = m_fileChooser.getSelectedFile();
try {
Scanner wordScanner = new Scanner(file);
wordScanner.useDelimiter("[^A-Za-z]+");
while (wordScanner.hasNext()) {
m_words.add(wordScanner.next());
}
//... Sort the words alphabetically.
Collections.sort(m_words);
|