import java.awt.*;
import java.io.*;
import javax.swing.*;



/**
 * A Frame that is used to view the contents of a file
 *
 * This class  uses the Singleton pattern 
 * to ensure that there is only one
 * instance at any point in time.  It differs from v1
 * in that it uses eager instantiation.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 2.0
 *
 */
public class FileViewer
{
    private Container    contentPane;
    private JFrame       f;
    private JLabel       header;
    private JScrollPane  scrollPane;
    private JTextArea    textArea;

//[eagerInstantiation.

    private static FileViewer   instance = new FileViewer();
//]eagerInstantiation.

    /**
     * Construct a new FileViewer
     *
     * Note: This method is private and used only internally
     */
    private FileViewer()
    {
	f = new JFrame();
	header = new JLabel("Contents of selected file:");
	textArea = new JTextArea();
	scrollPane = new JScrollPane(textArea);

	f.setTitle("James Madison University");

	textArea.setEditable(false);
	textArea.setLineWrap(true);
	textArea.setWrapStyleWord(true);

	contentPane = f.getContentPane();
	contentPane.setLayout(new BorderLayout());

	contentPane.add(header, BorderLayout.NORTH);
	contentPane.add(scrollPane, BorderLayout.CENTER);

	setSize(600,300);
	show();
    }

//[createInstance.

    /**
     * Return the singleton instance
     */
    public static FileViewer createInstance()
    {
	return instance;
    }
//]createInstance.


    /**
     * Load and view a new file
     *
     * @param fn  The name of the file to load and view
     */
    public void load(String fn)
    {
	BufferedReader  in;
	String          line, text;

	text = "";
	try 
        {
	    in = new BufferedReader(new FileReader(fn));

	    while ((line=in.readLine()) != null) 
            {
		text += line + "\n";
	    }
	    header.setText(fn);
	}
        catch (IOException ioe)
        {
	    header.setText("File not found!");
	    text = "";
	}

	textArea.setText(text);
    }



    /**
     * Set the size of this FileViewer
     *
     * @param width   The width (in pixels)
     * @param height  The height (in pixels)
     */
    public void setSize(int width, int height)
    {
	f.setSize(width, height);
    }




    /**
     * Show this FileViewer
     *
     */
    public void show()
    {
	f.setVisible(true);
    }

}
