Java Reference
In-Depth Information
The FileViewer class is designed to be used by other classes. It also has its own
main() method, however, so that it can be run as a standalone program.
Example 3−3: FileViewer.java
package com.davidflanagan.examples.io;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
/**
* This class creates and displays a window containing a TextArea,
* in which the contents of a text file are displayed.
**/
public class FileViewer extends Frame implements ActionListener {
String directory; // The default directory to display in the FileDialog
TextArea textarea; // The area to display the file contents into
/** Convenience constructor: file viewer starts out blank */
public FileViewer() { this(null, null); }
/** Convenience constructor: display file from current directory */
public FileViewer(String filename) { this(null, filename); }
/**
* The real constructor. Create a FileViewer object to display the
* specified file from the specified directory
**/
public FileViewer(String directory, String filename) {
super(); // Create the frame
// Destroy the window when the user requests it
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { dispose(); }
});
// Create a TextArea to display the contents of the file in
textarea = new TextArea("", 24, 80);
textarea.setFont(new Font("MonoSpaced", Font.PLAIN, 12));
textarea.setEditable(false);
this.add("Center", textarea);
// Create a bottom panel to hold a couple of buttons in
Panel p = new Panel();
p.setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 5));
this.add(p, "South");
// Create the buttons and arrange to handle button clicks
Font font = new Font("SansSerif", Font.BOLD, 14);
Button openfile = new Button("Open File");
Button close = new Button("Close");
openfile.addActionListener(this);
openfile.setActionCommand("open");
openfile.setFont(font);
close.addActionListener(this);
close.setActionCommand("close");
close.setFont(font);
p.add(openfile);
p.add(close);
this.pack();
Search WWH ::




Custom Search