32.7. Key Terms

 
[Page 994 ( continued )]

29.9. JFileChooser

The javax.swing.JFileChooser class displays a dialog box from which the user can navigate through the file system and select files for loading or saving, as shown in Figure 29.21.

Figure 29.21. The Swing JFileChooser shows files and directories, and enables the user to navigate through the file system visually.

Like JColorChooser , JFileChooser is a lightweight component inherited from JComponent . It can be added to any container if desired, but often you create an instance of JFileChooser and display it standalone.

JFileChooser is a subclass of JComponent . There are several ways to construct a file dialog box. The simplest is to use JFileChooser 's no-arg constructor.

The file dialog box can appear in two types: open and save. The open type is for opening a file, and the save type is for storing a file. To create an open file dialog, use the following method:

   public int   showOpenDialog(Component parent) 

This method creates a dialog box that contains an instance of JFileChooser for opening a file. The method returns an int value, either APPROVE_OPTION or CANCEL_OPTION , which indicates whether the OK button or the Cancel button was clicked.

Similarly, you can use the following method to create a dialog for saving files:

   public int   showSaveDialog(Component parent) 

The file dialog box created with showOpenDialog or showSaveDialog is modal. The JFileChooser class has the properties inherited from JComponent . It also has the following useful properties:

  • dialogType specifies the type of this dialog. Use OPEN_DIALOG when you want to bring up a file chooser that the user can use to open a file. Likewise, use SAVE_DIALOG to let the user choose a file for saving.

  • dialogTitle is the string that is displayed in the title bar of the dialog box.


    [Page 995]
  • currentDirectory is the current directory of the file. The type of this property is java.io.File . If you want the current directory to be used, use setCurrentDirectory(new File(".")) .

  • selectedFile is the file you have selected. You can use getSelectedFile() to return the selected file from the dialog box. The type of this property is java.io.File . If you have a default file name that you expect to use, use setSelectedFile(new File(filename)) .

  • selectedFiles is a list of the files selected if the file chooser is set to allow multi-selection. The type of this property is File[] .

  • multiSelectionEnabled is a boolean value indicating whether multiple files can be selected. By default, it is false .

Let us create an example of a simple text editor that uses Swing menus , tool bar, file chooser, and color chooser, as shown in Figure 29.22, which allows the user to open and save text files, clear text, and change the color and font of the text. Listing 29.8 shows the program.

Figure 29.22. The editor enables you to open and save text files from the File menu or from the tool bar, and to change the color and font of the text from the Edit menu.

Listing 29.8. TextEditor.java
(This item is displayed on pages 995 - 998 in the print version)
 1   import   java.io.*; 2   import   java.awt.*; 3   import   java.awt.event.*; 4   import   javax.swing.*; 5 6   public class   TextEditor   extends   JApplet { 7  // Declare and create image icons  8   private   ImageIcon openImageIcon = 9   new   ImageIcon(getClass().getResource(   "image/open.gif"   )); 10   private   ImageIcon saveImageIcon = 11   new   ImageIcon(getClass().getResource(   "image/save.gif"   )); 12 13  // Create menu items  14   private   JMenuItem jmiOpen =   new   JMenuItem(   "Open"   , openImageIcon); 15   private   JMenuItem jmiSave =   new   JMenuItem(   "Save"   , saveImageIcon); 16   private   JMenuItem jmiClear =   new   JMenuItem(   "Clear"   ); 17   private   JMenuItem jmiExit =   new   JMenuItem(   "Exit"   ); 18   private   JMenuItem jmiForeground =   new   JMenuItem(   "Foreground"   ); 19   private   JMenuItem jmiBackground =   new   JMenuItem(   "Background"   ); 20 21  // Create buttons to be placed in a tool bar  22   private   JButton jbtOpen =   new   JButton(openImageIcon); 23   private   JButton jbtSave =   new   JButton(saveImageIcon); 24   private   JLabel jlblStatus =   new   JLabel(); 

[Page 996]
 25 26  // Create a JFileChooser with the current directory  27    private   JFileChooser jFileChooser1  28  =   new   JFileChooser(   new   File(   "."   ));  29 30  // Create a text area  31   private   JTextArea jta =   new   JTextArea(); 32 33   public   TextEditor() { 34  // Add menu items to the menu  35 JMenu jMenu1 =   new   JMenu(   "File"   ); 36 jMenu1.add(jmiOpen); 37 jMenu1.add(jmiSave); 38 jMenu1.add(jmiClear); 39 jMenu1.addSeparator(); 40 jMenu1.add(jmiExit); 41 42  // Add menu items to the menu  43 JMenu jMenu2 =   new   JMenu(   "Edit"   ); 44 jMenu2.add(jmiForeground); 45 jMenu2.add(jmiBackground); 46 47  // Add menus to the menu bar  48 JMenuBar jMenuBar1 =   new   JMenuBar(); 49 jMenuBar1.add(jMenu1); 50 jMenuBar1.add(jMenu2); 51 52  // Set the menu bar  53 setJMenuBar(jMenuBar1); 54 55  // Create tool bar  56 JToolBar jToolBar1 =   new   JToolBar(); 57 jToolBar1.add(jbtOpen); 58 jToolBar1.add(jbtSave); 59 60  jmiOpen.addActionListener(   new   ActionListener()  { 61   public void   actionPerformed(ActionEvent e) { 62  open();  63 } 64 }); 65 66  jmiSave.addActionListener(   new   ActionListener()  { 67   public void   actionPerformed(ActionEvent evt) { 68  save();  69 } 70 }); 71 72 jmiClear.addActionListener(   new   ActionListener() { 73   public void   actionPerformed(ActionEvent evt) { 74 jta.setText(   null   ); 75 } 76 }); 77 78 jmiExit.addActionListener(   new   ActionListener() { 79   public void   actionPerformed(ActionEvent evt) { 80 System.exit(     ); 81 } 82 }); 83 

[Page 997]
 84  jmiForeground.addActionListener(   new   ActionListener()  { 85   public void   actionPerformed(ActionEvent evt) { 86 Color selectedColor = 87  JColorChooser.showDialog(   null   ,   "Choose Foreground Color"   ,  88  jta.getForeground());  89 90   if   (selectedColor !=   null   ) 91 jta.setForeground(selectedColor); 92 } 93 }); 94 95  jmiBackground.addActionListener(   new   ActionListener()  { 96   public void   actionPerformed(ActionEvent evt) { 97 Color selectedColor = 98  JColorChooser.showDialog(   null   ,   "Choose Background Color"   ,  99  jta.getForeground());  100 101   if   (selectedColor !=   null   ) 102 jta.setBackground(selectedColor); 103 } 104 }); 105 106  jbtOpen.addActionListener(   new   ActionListener()  { 107   public void   actionPerformed(ActionEvent evt) { 108  open();  109 } 110 }); 111 112  jbtSave.addActionListener(   new   ActionListener()  { 113   public void   actionPerformed(ActionEvent evt) { 114  save();  115 } 116 }); 117 118 add(jToolBar1, BorderLayout.NORTH); 119 add(jlblStatus, BorderLayout.SOUTH); 120 add(   new   JScrollPane(jta), BorderLayout.CENTER); 121 } 122 123  /** Open file */  124   private      void   open()  { 125   if   (  jFileChooser1.showOpenDialog(   this   ) ==  126  JFileChooser.APPROVE_OPTION  ) 127 open(jFileChooser1.getSelectedFile()); 128 } 129 130  /** Open file with the specified File instance */  131   private      void   open(File file)  { 132   try   { 133  // Read from the specified file and store it in jta  134 BufferedInputStream in =   new   BufferedInputStream( 135   new   FileInputStream(file)); 136   byte   [] b =   new byte   [in.available()]; 137 in.read(b,     , b.length); 138 jta.append(   new   String(b,     , b.length)); 139 in.close(); 140 141  // Display the status of the Open file operation in jlblStatus  142 jlblStatus.setText(file.getName() +   " Opened"   ); 143 } 

[Page 998]
 144   catch   (IOException ex) { 145 jlblStatus.setText(   "Error opening "   + file.getName()); 146 } 147 } 148 149  /** Save file */  150   private      void   save()  { 151   if   (  jFileChooser1.showSaveDialog(   this   ) ==  152  JFileChooser.APPROVE_OPTION  ) { 153 save(jFileChooser1.getSelectedFile()); 154 } 155 } 156 157  /** Save file with specified File instance */  158   private      void   save(File file)  { 159   try   { 160  // Write the text in jta to the specified file  161 BufferedOutputStream out =   new   BufferedOutputStream( 162   new   FileOutputStream(file)); 163   byte   [] b = (jta.getText()).getBytes(); 164 out.write(b,     , b.length); 165 out.close(); 166 167  // Display the status of the save file operation in jlblStatus  168 jlblStatus.setText(file.getName() +   " Saved "   ); 169 } 170   catch   (IOException ex) { 171 jlblStatus.setText(   "Error saving "   + file.getName()); 172 } 173 } 174 } 

The program creates the File and Edit menus (lines 34 “45). The File menu contains the menu commands Open for loading a file, Save for saving a file, Clear for clearing the text editor, and Exit for terminating the program. The Edit menu contains the menu commands Foreground Color and Background Color for setting foreground color and background color in the text. The Open and Save menu commands can also be accessed from the tool bar, which is created in lines 56 “58. The status of executing Open and Save is displayed in the status label, which is created in line 24.

jFileChooser1 , an instance of JfileChooser , is created for displaying the file dialog box to open and save files (lines 27 “28). new File(".") is used to set the current directory to the directory where the class is stored.

The open method is invoked when the user clicks the Open menu command or the Open tool bar button (lines 62, 108). The showOpenDialog method (line 125) displays an Open dialog box, as shown in Figure 29.21. Upon receiving the selected file, the method open(file) (line 127) is invoked to load the file to the text area using a BufferedInputStream wrapped on a FileInputStream .

The save method is invoked when the user clicks the Save menu command or the Save tool bar button (lines 68, 114). The showSaveDialog method (line 151) displays a Save dialog box. Upon receiving the selected file, the method save(file) (line 153) is invoked to save the contents from the text area to the file using a BufferedOutputStream wrapped on a FileOutputStream .

The color dialog is displayed using the static method showDialog (lines 87, 98) of JColorChooser . Thus you don't need to create an instance of JFileChooser . The showDialog method returns the selected color if the OK button is clicked after a color is selected.

 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net