23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Java</strong> I/O<br />

mixed AWT components with the Swing JFileChooser rapidly crashed the VM. Replacing<br />

all components with their Swing equivalents solved the problem.<br />

Let's begin the exegesis of the code where I began writing it, with the user interface. The main<br />

driver class is FileViewer, shown in Example 13.12. This class extends JFrame. Its<br />

constructor doesn't do a lot. Most of the work is relegated to the init() method, which sets<br />

up the user interface composed of the three parts previously described, then centers the whole<br />

frame on the primary display.<br />

Example 13.12. FileViewer<br />

import javax.swing.*;<br />

import java.io.*;<br />

import com.macfaq.io.*;<br />

import com.macfaq.swing.*;<br />

import java.awt.*;<br />

import java.awt.event.*;<br />

public class FileViewer extends JFrame<br />

implements WindowListener, ActionListener {<br />

JFileChooser fc = new JFileChooser();<br />

JStreamedTextArea theView = new JStreamedTextArea();<br />

ModePanel mp = new ModePanel();<br />

public FileViewer() {<br />

super("FileViewer");<br />

}<br />

public void init() {<br />

}<br />

this.addWindowListener(this);<br />

fc.setApproveButtonText("View File");<br />

fc.setApproveButtonMnemonic('V');<br />

fc.addActionListener(this);<br />

this.getContentPane().add("Center", fc);<br />

JScrollPane sp = new JScrollPane(theView);<br />

this.getContentPane().add("South", sp);<br />

this.getContentPane().add("West", mp);<br />

this.pack();<br />

// Center on display.<br />

Dimension display = getToolkit().getScreenSize();<br />

Dimension bounds = this.getSize();<br />

int x = (display.width - bounds.width)/2;<br />

int y = (display.height - bounds.height)/2;<br />

if (x < 0) x = 10;<br />

if (y < 0) y = 15;<br />

this.setLocation(x, y);<br />

public void actionPerformed(ActionEvent e) {<br />

if (e.getActionCommand().equals(JFileChooser.APPROVE_SELECT<strong>IO</strong>N)) {<br />

File f = fc.getSelectedFile();<br />

if (f != null) {<br />

332

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!