Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 99 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
99
Dung lượng
870,04 KB
Nội dung
Java Swing – O’Reilly - 298 - import java.net.*; import java.beans.*; import java.io.*; import java.applet.*; import java.awt.event.*; // Caveat programmer: you should replace this with a JMF equivalent when that's // ready for all of your delivery platforms. import sun.applet.*; public class AudioAccessory extends JPanel implements PropertyChangeListener { AudioClip currentClip; String currentName=""; JLabel fileLabel; JButton playButton, stopButton; public AudioAccessory() { // Set up the accessory. The file chooser will give us a reasonable size. setLayout(new BorderLayout()); add(fileLabel = new JLabel("Clip Name"), BorderLayout.NORTH); JPanel p = new JPanel(); playButton = new JButton("Play"); stopButton = new JButton("Stop"); playButton.setEnabled(false); stopButton.setEnabled(false); p.add(playButton); p.add(stopButton); add(p, BorderLayout.CENTER); playButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (currentClip != null) { currentClip.stop(); currentClip.play(); } } }); stopButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (currentClip != null) { currentClip.stop(); } } }); } public void propertyChange(PropertyChangeEvent e) { if (e.getPropertyName() .equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) { // Ok, the user selected a file in the chooser File f = (File)e.getNewValue(); // Make reasonably sure it's an audio file if (f.getName().toLowerCase().endsWith(".au")) { setCurrentClip(f); } else { setCurrentClip(null); } } } Java Swing – O’Reilly - 299 - public void setCurrentClip(File f) { // Make sure we have a real file, otherwise, disable the buttons if ((f == null) || (f.getName() == null)) { fileLabel.setText("no audio selected"); playButton.setEnabled(false); stopButton.setEnabled(false); return; } // Ok, seems the audio file is real, so load it and enable the buttons String name = f.getName(); if (name.equals(currentName)) { return; } if (currentClip != null) { currentClip.stop(); } currentName = name; try { URL u = new URL("file:///" + f.getAbsolutePath()); currentClip = new AppletAudioClip(u); } catch (Exception e) { e.printStackTrace(); currentClip = null; fileLabel.setText("Error loading clip."); } fileLabel.setText(name); playButton.setEnabled(true); stopButton.setEnabled(true); } } And here's the application code that inserts the accessory into the chooser. The only real change we make is to the open button's actionPerformed() method. Before we make the chooser visible, we use setAccessory() to get our audio accessory in place. Then we attach the accessory as a property change listener to the chooser, so that the accessory is appropriately notified as the user selects new files. // AccessoryFileChooser.java, just a simple file chooser example // to see what it takes to make one of these work. // import java.awt.*; import java.awt.event.*; import java.io.*; import javax.swing.*; public class AccessoryFileChooser extends JFrame { JFrame parent; public AccessoryFileChooser() { super("Accessory Test Frame"); setSize(350, 200); addWindowListener(new BasicWindowMonitor()); parent = this; Container c = getContentPane(); c.setLayout(new FlowLayout()); Java Swing – O’Reilly - 300 - JButton accButton = new JButton("Accessory"); final JLabel statusbar = new JLabel("Output of your selection will go here"); accButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JFileChooser chooser = new JFileChooser(); AudioAccessory aa = new AudioAccessory(); chooser.setAccessory(aa); chooser.addPropertyChangeListener(aa); int option = chooser.showOpenDialog(parent); if (option == JFileChooser.APPROVE_OPTION) { statusbar.setText("You chose " + ((chooser.getSelectedFile()!=null)? chooser.getSelectedFile().getName():"nothing")); } else { statusbar.setText("You canceled."); } } }); c.add(accButton); c.add(statusbar); } public static void main(String args[]) { AccessoryFileChooser afc = new AccessoryFileChooser(); afc.setVisible(true); } } 12.1.2 Events In addition to the property change events generated like most other Swing components, the JFileChooser also generates action events when the user presses the approve or cancel buttons. The event is fired after the dialog is hidden. public void addActionListener(ActionListener l) public void removeActionListener(ActionListener l) If you want to listen directly to the approve or cancel button events, you can add an ActionListener to the dialog. The accessory example listened to such events to stop playing any active audio clip. public void approveSelection() public void cancelSelection() You can programmatically fire an approval or a cancellation using these methods, simulating pressing the "Ok" or "Cancel" buttons. This can be useful if your accessory provides its own way of saying yes or no to the current selection. Both methods use the fireActionPerformed() method below to send out the events. The APPROVE_SELECTION and CANCEL_SELECTION constants listed later are used for the appropriate command string. protected void fireActionPerformed(String command) This protected method fires off a newly generated ActionEvent with the given command as the actionCommand of the event. Java Swing – O’Reilly - 301 - 12.1.3 Constants The JFileChooser class has several constants. These constants can be broken into two categories: • The constants used for property change events, shown in Table 12.2 • The constants used as various property values, shown in Table 12.3 Table 12.2, FileChooser Property Names (for Property Change Events) Constant Type Description ACCESSORY_CHANGED_PROPERTY String The name of the accessory property APPROVE_BUTTON_MNEMONIC_CHANGED_PROPERTY String The name of the approveButtonMnemonic property APPROVE_BUTTON_TEXT_CHANGED_PROPERTY String The name of the approveButtonText property APPROVE_BUTTON_TOOL_TIP_TEXT_CHANGED_PROPERTY String The name of the approveButtonToolTipText property CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY String The name of the choosableFile- Filters property DIALOG_TYPE_CHANGED_PROPERTY String The name of the dialogType property DIRECTORY_CHANGED_PROPERTY String The name of the currentDirectory property FILE_FILTER_CHANGED_PROPERTY String The name of the fileFilter property FILE_HIDING_CHANGED_PROPERTY String The name of the fileHidingEnabled property FILE_SELECTION_MODE_CHANGED_PROPERTY String The name of the fileSelectionMode property FILE_SYSTEM_VIEW_CHANGED_PROPERTY String The name of the fileSystemView property FILE_VIEW_CHANGED_PROPERTY String The name of the fileView property MULTI_SELECTION_ENABLED_CHANGED_PROPERTY String The name of the multiSelectionEnabled property SELECTED_FILE_CHANGED_PROPERTY String The name of the selectedFileproperty The constants in Table 12.3 provide values for many of the properties in the JFileChooser class. Table 12.3, FileChooser Dialog Constants Constant Type Description APPROVE_OPTION int The return value from the showDialog() methods, indicating the user selected the "approve" option APPROVE_SELECTION String The string to be used for the actionCommand property of the ActionEvent generated when the user approves the current selection CANCEL_OPTION int The return value from the showDialog() methods, indicating the user selected the "cancel" option CANCEL_SELECTION String The string to be used for the actionCommand property of the ActionEvent generated when the user cancels the current selection CUSTOM_DIALOG String A valid option for the property, indicating this dialog supports a user-defined operation DIRECTORIES_ONLY int A valid option for the fileSelectionMode property, indicating that only directories can be selected ERROR_OPTION int The return value from the showDialog() methods, indicating an error Java Swing – O’Reilly - 302 - occurred FILES_AND_DIRECTORIES int A valid option for the fileSelectionMode property, indicating that both files and directories can be selected FILES_ONLY int A valid option for the fileSelectionMode property, indicating that only files can be selected OPEN_DIALOG int A valid option for the property, indicating this dialog is selecting files to be opened SAVE_DIALOG int A valid option for the property, indicating this dialog is selecting a file to be saved 12.1.4 Constructors public JFileChooser() Creates a file chooser starting at the user's home directory. File choosers do not make a distinction between open and save at creation time. That aspect of a chooser is dictated by the dialogType property, which can be set at any time. public JFileChooser(File directory) public JFileChooser(String path) These constructors create new choosers starting at the specified directory. 12.1.5 FileFilter Methods The choosableFileFilters property does not have a proper "set" method, but you can modify the set of available filters using these methods. public void addChoosableFileFilter(FileFilter filter) public void removeChoosableFileFilter(FileFilter filter) Add or remove filters. The FileFilter class is discussed in detail below. public void resetChoosableFileFilters() Resets the list of choosable file filters to contain only the original "accept all" filter. 12.1.6 File Methods The file methods check files to find the appropriate names, descriptions and icons to display in the chooser according to the active FileView and FileFilter objects. public boolean accept(File f) Returns true if the file f should be displayed. public void ensureFileIsVisible(File f) Ensures the file f is visible in the chooser, which may mean changing the scroll location of the file list. public String getDescription(File f) Java Swing – O’Reilly - 303 - Returns a description of the file f. A common description is simply the file's name. public Icon getIcon(File f) Returns an icon to display in the chooser for the file f. The icon could change depending on the type of file. public String getName(File f) Returns the name of the file f. The chooser relies on the active FileView object to decide a file's name. The FileView object could alter the file's name for display, for example, to create an ISO 9660 compliant name. public String getTypeDescription(File f) Returns a brief description of the type of file f. The details view of a directory might use this information. public boolean isTraversable(File f) Returns true if the file is a folder and can be opened. 12.1.7 Dialog Methods public int showDialog(Component parent, String approveButtonText) Makes the dialog visible. If parent is not an instance of Frame, then the containing Frame object for parent is located and used. This method returns 0 if the user accepts a file, -1 if the user cancels or otherwise closes the dialog. Use this version of showDialog() to create a custom dialog that has text you specify for the "Ok" button (as opposed to one of the other show methods below). public int showOpenDialog(Component parent) public int showSaveDialog(Component parent) You can use these methods to display chooser dialogs that have "Open" or "Save" on the approve button. The dialogs will be shown relative to the parent component. 12.1.8 Miscellaneous Methods public void changeToParentDirectory() Programmatically moves the current directory up one level. At the root level, this method has no effect. protected void init() Initializes the properties of the dialog and picks the default file view for your system. public void rescanCurrentDirectory() Reloads the current directory if its contents have changed. Java Swing – O’Reilly - 304 - public void updateUI() Updates the chooser dialog with the look-and-feel dictated by the UI manager. 12.2 The File Chooser Package Under javax.swing, you'll find a package of helper classes for the JFileChooser. The javax.swing.filechooser package contains several classes for displaying and filtering files. (More classes are planned for this package, but they are currently located in the file chooser demo area in the examples/ directory of the Swing download package.) 12.2.1 The FileFilter Class The FileFilter class can be used to create filters for JFileChooser dialogs. The class contains only two abstract methods, but default implementations based on filename extensions should become a standard part of the Swing package with the next release. It's important to note that extensions are not the only way to judge a file's fitness for a particular filter. The Mac filesystem, for example, can understand the creator of a file regardless of the file's name. On Unix systems, you might write a filter to display only files that are readable by the current user. 12.2.1.1 Constructors public FileFilter() The FileFilter class receives this default constructor at compile time, it is not defined in the class itself. 12.2.1.2 Filter Methods public abstract boolean accept(File f) Returns true if the file f matches this filter. public abstract String getDescription() Returns a short description to appear in the filters pull-down on the chooser. An example would be "Java Source Code" for any .java files. Figure 12.5 shows a file chooser with custom filters for multimedia file types. Figure 12.5. A custom set of filters for use with JFileChooser Java Swing – O’Reilly - 305 - Here's the code for the application. Before we make this chooser visible, we create and insert the three new filters for our media types. Other than that, it's much the same code as our previous applications. In a future release of Swing, you should have access to a similar extension-based file filter class. However, we use this example anyway, as it illustrates the inner workings of a filter that should seem familiar to most programmers. // MyFilterChooser.java // Just a simple example to see what it takes to make one of these filters work. // import java.awt.*; import java.awt.event.*; import java.io.*; import javax.swing.*; public class MyFilterChooser extends JFrame { JFrame parent; public MyFilterChooser() { super("Filter Test Frame"); setSize(350, 200); addWindowListener(new BasicWindowMonitor()); parent = this; Container c = getContentPane(); c.setLayout(new FlowLayout()); JButton openButton = new JButton("Open"); final JLabel statusbar = new JLabel("Output of your selection will go here"); openButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String[] pics = new String[] {"gif", "jpg", "tif"}; String[] movies = new String[] {"mov", "avi"}; String[] audios = new String[] {"au", "aiff", "wav"}; JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(false); Java Swing – O’Reilly - 306 - chooser.addChoosableFileFilter(new SimpleFileFilter(pics, "Images (*.gif, *.jpg, *.tif)")); chooser.addChoosableFileFilter(new SimpleFileFilter(movies, "Movies (*.mov, *.avi)")); chooser.addChoosableFileFilter(new SimpleFileFilter(audios, "Sounds (*.aiff, *.au, *.wav)")); int option = chooser.showOpenDialog(parent); if (option == JFileChooser.APPROVE_OPTION) { if (chooser.getSelectedFile()!=null) statusbar.setText("You chose " + chooser.getSelectedFile().getName()); } else { statusbar.setText("You canceled."); } } }); c.add(openButton); c.add(statusbar); setVisible(true); } public static void main(String args[]) { MyFilterChooser bt = new MyFilterChooser(); } } And here is the implementation of the filter class. You pass in an extension (or list of extensions) and a description of the extension to the constructor. If you don't supply a description, the constructor builds a simple one for you based on the extensions you passed in. The only real work this class does happens in the accept() method, where we look to see if the file presented matches one of the supplied extensions. // SimpleFileFilter.java // A straightforward extension-based example of a file filter. This should be // replaced by a "first class" Swing class in a later release of Swing. // import javax.swing.filechooser.*; import java.io.File; public class SimpleFileFilter extends FileFilter { String[] extensions; String description; public SimpleFileFilter(String ext) { this (new String[] {ext}, null); } public SimpleFileFilter(String[] exts, String descr) { // clone and lowercase the extensions extensions = new String[exts.length]; for (int i = exts.length - 1; i >= 0; i ) { Java Swing – O’Reilly - 307 - extensions[i] = exts[i].toLowerCase(); } // make sure we have a valid (if simplistic) description description = (descr == null ? exts[0] + " files" : descr); } public boolean accept(File f) { // we always allow directories, regardless of their extension if (f.isDirectory()) { return true; } // ok, it's a regular file so check the extension String name = f.getName().toLowerCase(); for (int i = extensions.length - 1; i >= 0; i ) { if (name.endsWith(extensions[i])) { return true; } } return false; } public String getDescription() { return description; } } 12.2.2 The FileView Class Another abstract helper class in the filechooser package is the FileView class. This class is implemented by the various look-and-feels to supply icons and descriptions for the basic file and folder entries in the filesystem. While each look-and-feel has a default implementation of this class, you can write your own and attach it to a file chooser to supply custom icons and descriptions for interesting types of files. 12.2.2.1 Constructor public FileView() The FileView class has only this default constructor. 12.2.2.2 Methods All of the methods for the FileView class are abstract and take one File as an argument. You fill in these methods to present a clean, consistent view of all files throughout the file chooser. Most views end up making decisions based on file information, such as the file's name or extension, before returning its result. public abstract String getName(File f) Returns the name of the file f. While it's quite easy to return f.getName(), you might want to return an all-uppercase version, or a cross-platform CD-ROM-compliant (ISO 9660) name, etc. public abstract String getDescription(File f) [...]... FontChooser .java // A font chooser that allows users to pick a font by name, size, style, and // color The color selection will be provided by a JColorChooser pane This // dialog builds an AttributeSet suitable for use with JTextPane // import javax .swing. *; import javax .swing. event.*; import javax .swing. colorchooser.*; import javax .swing. text.*; import java. awt.*; import java. awt.event.*; - 323 - Java Swing. .. custom chooser panel added directly to a JColorChooser object - 319 - Java Swing – O’Reilly // GrayScalePanel .java // A simple implementation of the AbstractColorChooserPanel class This class // provides a slider for picking out a shade of gray // import java. awt.*; import javax .swing. *; import javax .swing. event.*; import javax .swing. colorchooser.*; public class GrayScalePanel extends AbstractColorChooserPanel... event handler Notice how the application does indeed check the new font choice to see if it is null or not // - 326 - Java Swing – O’Reilly FontPicker .java // A quick test of the JColorChooser dialog // import java. awt.*; import java. awt.event.*; import javax .swing. *; import javax .swing. colorchooser.*; public class FontPicker extends JFrame { JFrame parent; Color c; public FontPicker() { super("JColorChooser... 16x16 image of // each GIF or JPG file for its icon This could be SLOW for large images, as we // simply load the real image and then scale it // import java. io.File; import java. awt.*; import javax .swing. *; import javax .swing. filechooser.*; import javax .swing. plaf.metal.MetalIconFactory; public class ThumbNailFileView extends FileView { private Icon fileIcon = MetalIconFactory.getTreeLeafIcon(); private... only real change is that we manually build the list of chooser panels for our chooser in the ColorPicker2 constructor: // ColorPicker2 .java // A quick test of the JColorChooser dialog // import java. awt.*; import java. awt.event.*; import javax .swing. *; import javax .swing. colorChooser.*; public class ColorPicker2 extends JFrame { JFrame parent; Color c; public ColorPicker2() { super("JColorChooser Test... within the Swing hierarchy: javax .swing. border Figure 13.2 shows the classes within this package All Swing borders directly or indirectly extend the AbstractBorder class, which in turn implements the more fundamental Border interface The Border interface outlines a minimal set of methods that Swing requires for an object to qualify as a border Figure 13.2 Border class diagram - 328 - Java Swing – O’Reilly... selected color changes 12.3.2 .4 Constructors public DefaultColorSelectionModel() public DefaultColorSelectionModel(Color color) These constructors create new DefaultColorSelectionModel objects If you call the first constructor with no color, Color.white is used - 315 - Java Swing – O’Reilly 12 .4 The JColorChooser Class 12 .4. 1 Properties In addition to the typical UI properties of Swing components, the color... implementation The only real change from the previous applications is in the properties we set for the chooser // MyViewChooser .java // A simple example to see what it takes to make one of these FileViews work // import java. awt.*; import java. awt.event.*; import java. io.*; import javax .swing. *; public class MyViewChooser extends JFrame { JFrame parent; public MyViewChooser() { super("File View Test Frame");... red, blue, and green using sliders The standard color chooser window looks like Figure 12.7. [4] - 312 - Java Swing – O’Reilly [4] JColorChooser has had a complicated history It disappeared briefly into a preview package, and then returned for JDK 1.2 beta4 in a completely different form We discuss the JDK 1.2 beta4 chooser Figure 12.7 The default JColorChooser dialog in Swatches (top) and RGB (bottom)... class provides a static method for getting this popup going quickly Here's the code that produced the screen shots in Figure 12.7: // ColorPicker .java // A quick test of the JColorChooser dialog // import java. awt.*; import java. awt.event.*; import javax .swing. *; public class ColorPicker extends JFrame { public ColorPicker() { super("JColorChooser Test Frame"); setSize(200, 100); final JButton go = . real image and then scale it. // import java. io.File; import java. awt.*; import javax .swing. *; import javax .swing. filechooser.*; import javax .swing. plaf.metal.MetalIconFactory; public. Java Swing – O’Reilly - 298 - import java. net.*; import java. beans.*; import java. io.*; import java. applet.*; import java. awt.event.*; // Caveat programmer:. MyFilterChooser .java // Just a simple example to see what it takes to make one of these filters work. // import java. awt.*; import java. awt.event.*; import java. io.*; import javax .swing. *;