17.15. File Selection Dialog
A
JFileChooser
is a standard
Selecting files all day can be pretty boring without a greater purpose, so we'll exercise the JFileChooser in a mini-editor application. Editor provides a text area in which we can load and work with files. (The JFileChooser created by Editor is shown in Figure 17-14.) We'll stop just shy of the capability to save and let you fill in the blanks (with a few caveats). Figure 17-14. Using a JFileChooser
Here's the code:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class Editor extends JFrame implements ActionListener
{
private JEditorPane textPane = new JEditorPane( );
public Editor( ) {
super("Editor v1.0");
Container content = getContentPane( ); // unnecessary in 5.0+
content.add(new JScrollPane(textPane), BorderLayout.CENTER);
JMenu menu = new JMenu("File");
menu.add(makeMenuItem("Open"));
menu.add(makeMenuItem("Save"));
menu.add(makeMenuItem("Quit"));
JMenuBar menuBar = new JMenuBar( );
menuBar.add(menu);
setJMenuBar(menuBar);
setSize(300, 300);
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand( );
if (command.equals("Quit")) System.exit(0);
else if (command.equals("Open")) loadFile( );
else if (command.equals("Save")) saveFile( );
}
private void loadFile ( ) {
JFileChooser chooser = new JFileChooser( );
int result = chooser.showOpenDialog(this);
if (result == JFileChooser.CANCEL_OPTION) return;
try {
File file = chooser.getSelectedFile( );
java.net.URL url = file.toURL( );
textPane.setPage(url);
}
catch (Exception e) {
textPane.setText("Could not load file: " + e);
}
}
private void saveFile( ) {
JFileChooser chooser = new JFileChooser( );
chooser.showSaveDialog(this);
// Save file data...
}
private JMenuItem makeMenuItem( String name ) {
JMenuItem m = new JMenuItem( name );
m.addActionListener( this );
return m;
}
public static void main(String[] s) {
new Editor( ).setVisible(true);
}
}
Editor is a JFrame that lays itself out with a JEditorPane (which is covered in Chapter 18) and a pull-down menu. From the pull-down File menu, we can Open, Save, or Quit. The actionPerformed( ) method catches the events associated with these menu selections and takes the appropriate action.
The interesting
A
JFileChooser
does its work when the
showOpenDialog( )
method is called. This method blocks the caller until the dialog completes its job, at which time the file chooser disappears. After that, we can retrieve the designated file with the
getFile( )
method. In
loadFile( )
, we convert the selected
File
to a
URL
and pass it to the
JEditorPane
, which displays the selected file. As you'll learn in the
You can fill out the
|