Java Reference
In-Depth Information
Listing 9-13 demonstrates a simple window with two labels and a JFileChooser . Notice
that there are no Open or Cancel buttons, but the buttons in the FileSystemView area are selectable.
Listing 9-13. Using a JFileChooser in Your JFrame
import java.io.File;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FileSamplePanel {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("JFileChooser Popup");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JLabel directoryLabel = new JLabel(" ");
directoryLabel.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 36));
frame.add(directoryLabel, BorderLayout.NORTH);
final JLabel filenameLabel = new JLabel(" ");
filenameLabel.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 36));
frame.add(filenameLabel, BorderLayout.SOUTH);
JFileChooser fileChooser = new JFileChooser(".");
fileChooser.setControlButtonsAreShown(false);
frame.add(fileChooser, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
Adding an ActionListener to a JFileChooser
The JFileChooser allows you to add ActionListener objects to listen for selection of the approval or
cancel actions. Approval is double-clicking a file; cancel is pressing the Escape key. To detect
which action was triggered, check the action command for the ActionEvent received by your
ActionListener . Its action command setting will be either JFileChooser.APPROVE_SELECTION
for file selection or JFileChooser.CANCEL_SELECTION for pressing the Escape key.
To complete the previous example in Listing 9-13, adding an ActionListener allows you to
set the text for the two labels when the user selects a file. On selection, the text becomes the
Search WWH ::




Custom Search