Source of FileDisplayGUIAppSwing.java


  1: //FileDisplayGUIAppSwing.java
  2: //Loads in a file and displays it in a JTextArea.

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

  9: class FileDisplayGUIAppSwing extends JFrame
 10: implements ActionListener
 11: {
 12:     private JScrollPane scrollPane;
 13:     private JTextArea   inputTextArea;
 14:     private JTextField  nameField;
 15:     private JButton     loadButton;

 17:     private BufferedReader inFile;

 19:     public static void main(String[] args)
 20:     {
 21:         FileDisplayGUIAppSwing app = new FileDisplayGUIAppSwing();
 22:         app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 23:         app.setSize(600, 400);
 24:         app. makeGui();
 25:         app.show();
 26:     }

 28:     public void makeGui()
 29:     {
 30:         JPanel top = new JPanel();

 32:         loadButton =
 33:             new JButton("Enter name of file and click this button to load it: ");
 34:         loadButton.addActionListener(this);
 35:         top.add(loadButton);

 37:         nameField = new JTextField(20);
 38:         top.add(nameField);
 39:         getContentPane().add(top, BorderLayout.NORTH);

 41:         inputTextArea = new JTextArea();
 42:         scrollPane = new JScrollPane(inputTextArea,
 43:                 ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
 44:                 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
 45:         getContentPane().add(scrollPane, BorderLayout.CENTER);
 46:     }

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

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