Source of FileDisplayGUIAppAWT.java


  1: //FileDisplayGUIAppAWT.java
  2: //Loads in a file and displays it in a TextArea.

  4: import java.io.*;
  5: import java.awt.*;
  6: import java.awt.event.*;

  8: class FileDisplayGUIAppAWT extends Frame
  9: implements ActionListener,
 10:            WindowListener
 11: {
 12:     private TextArea  inputTextArea;
 13:     private TextField nameField;
 14:     private Button    loadButton;

 16:     private BufferedReader inFile;

 18:     public static void main(String[] args)
 19:     {
 20:         FileDisplayGUIAppAWT app = new FileDisplayGUIAppAWT();
 21:         app.setSize(450, 400);
 22:         app. makeGui();
 23:         app.setVisible(true);
 24:     }

 26:     public void makeGui()
 27:     {
 28:         Panel top = new Panel();

 30:         loadButton =
 31:             new Button("Click this button to load this file: ");
 32:         loadButton.addActionListener(this);
 33:         top.add(loadButton);

 35:         nameField = new TextField(20);
 36:         nameField.addActionListener(this);
 37:         top.add(nameField);
 38:         add ("North", top);

 40:         inputTextArea = new TextArea("");
 41:         add ("Center", inputTextArea);

 43:         addWindowListener(this);
 44:     }

 46: 
 47:     public void actionPerformed(ActionEvent e)
 48:     {
 49:         if (e.getSource() == loadButton)
 50:         {
 51:             String fileName = nameField.getText();
 52:             try
 53:             {
 54:                 inFile = new
 55:                     BufferedReader(new FileReader(fileName));
 56:                 inputTextArea.setText(""); //Clear the input area

 58:                 String line;
 59:                 while ((line = inFile.readLine()) != null)
 60:                     inputTextArea.append(line + "\n");
 61:                 inputTextArea.setCaretPosition(0);
 62:                 inputTextArea.setEditable(false);
 63:                 inputTextArea.setBackground(Color.white);
 64:                 inFile.close();
 65:             }
 66:             catch (IOException eIO)
 67:             {
 68:                 System.err.println("Error in file " +
 69:                                    fileName         +
 70:                                    ": " + eIO.toString());
 71:                 System.exit(1);
 72:             }
 73:         }
 74:     }


 77:     public void windowClosing(WindowEvent e)
 78:     {
 79:         System.exit(0);
 80:     }
 81:     //Empty WindowListener methods
 82:     public void windowIconified(WindowEvent e)   {}
 83:     public void windowOpened(WindowEvent e)      {}
 84:     public void windowClosed(WindowEvent e)      {}
 85:     public void windowDeiconified(WindowEvent e) {}
 86:     public void windowActivated(WindowEvent e)   {}
 87:     public void windowDeactivated(WindowEvent e) {}
 88: }