Solved

Problem with FileChooser & Accessory

Posted on 2004-03-23
9
770 Views
Last Modified: 2013-11-23
Hello to everyone out there. I hope that someone is out there to help me with this problem.
I don't seem to see where my problem is in getting the filechooser and the accessory to work together, I think it is simple but I am new at this.


import java.io.File;
   import javax.swing.*;

   public class MultiChooser {

     public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            JFileChooser chooser = new JFileChooser(".");
            fileChooser.setMultiSelectionEnabled(true);
            AudioFileDescriptionAccessory afda = new AudioFileDescriptionAccessory();
            chooser.setAccessory(afda);
            int status = chooser.showOpenDialog(null);
            if (status == JFileChooser.APPROVE_OPTION) {
                   File selectedFiles[] = chooser.getSelectedFiles();
               for (int i=0,
                    n=selectedFiles.length; i<n; i++) {
                         System.out.println("Selected: "
                         + selectedFiles[i].getParent()
                         + " --- "
                         + selectedFiles[i].getName());
               }
            }
            System.exit(0);
          }
       });
     }
   }





// AudioFileDescriptionAccessory// An accessory for JFileChooser that plays music clips and has a file description

import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.beans.*;
import java.io.*;
import java.applet.*;
import java.awt.event.*;

public class AudioFileDescriptionAccessory(){


// Set up the accessory. The file chooser will give us a reasonable size.

public AudioFileDescriptionAccessory{
audioLabel = new JLabel("Audio Controls");
playButton = new JButton("Play");
stopButton = new JButton("Stop");
fileLabel = new JLabel("File Description");
textArea = new JTextArea(
"This is an editable JTextArea. " +
"A text area is a \"plain\" text component, " +
"which means that although it can display text " +
"in any font, all of the text is in the same font.");
JScrollPane jspane = new JScrollPane(textArea);

playButton.setEnabled(false);
stopButton.setEnabled(false);
textArea.setFont(new Font("Serif", Font.PLAIN, 12));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
jspane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jspane.setPreferredSize(new Dimension(150, 60));
jspane.getViewport().add(textArea);

JPanel p0 = new JPanel(new BorderLayout());
JPanel p1 = new JPanel(new BorderLayout());
JPanel p2 = new JPanel(new BorderLayout());
JPanel p3 = new JPanel(new BorderLayout());
JPanel p4 = new JPanel(new BorderLayout());

p0.add(audioLabel, BorderLayout.CENTER);
p1.add(playButton, BorderLayout.CENTER);
p2.add(stopButton, BorderLayout.CENTER);
p3.add(fileLabel, BorderLayout.CENTER);
p4.add(jspane, BorderLayout.CENTER);

p4.add(p3, BorderLayout.NORTH);
p3.add(p2, BorderLayout.NORTH);
p2.add(p1, BorderLayout.NORTH);
p1.add(p0, BorderLayout.NORTH);

setLayout(new FlowLayout());
add(p4);

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();
}
}
});
}

void saveasfile() {

String currFileName;

jFileChooser1.setVisible(true);

jFileChooser1.setEnabled(true);

if (JFileChooser.APPROVE_OPTION == jFileChooser1.showSaveDialog(this)) {

currFileName = jFileChooser1.getSelectedFile().getPath();

if (currFileName.endsWith(".doc") == false &&

currFileName.endsWith(".rtf") == false) {

currFileName = currFileName + ".doc";

}

try { File file = new File(currFileName);

FileWriter out = new FileWriter(file);

String text = jTextAreaRep.getText(); // GET YOUR TEXT FROM TEXT AREA..

out.write(text);

out.close();

JOptionPane.showMessageDialog(null, "The report has been saved to the file..",

"Saved", 1);

}

catch (IOException e) {

//System.out.println("Error saving " + currFileName);

}

}

jFileChooser1.setVisible(false);

jFileChooser1.setEnabled(false);

}


0
Comment
Question by:Drop_of_Rain
  • 4
  • 3
9 Comments
 
LVL 16

Expert Comment

by:krakatoa
ID: 10655992
Take a look at this code. I put it together as a demo, so you'll have to take bits out you dont want.

//------------------------------------------------------
import java.io.*;
import java.net.*;
import java.beans.*;
import javax.swing.*;
import java.awt.*;



public class UniversalFileSender extends JFrame implements Runnable {
 
    private int n;

    private File fileToSend;
 
    private byte[] buff;
   
    private BufferedOutputStream bos;
    private FileInputStream in;
 
    private Socket fileSocketOut;

    private final static String HOST = "127.0.0.1";
    private final static int PORT = 30000;
    private final static int BUFFER_SIZE = 1024;
     
    LabelAccessory accessory;
 
     
public UniversalFileSender (File fileToSend){
 

   

    this.fileToSend = fileToSend;
   
     


 
 }
 


 
public void run(){


this.setSize(200,200);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.show();

///*
int intt;
javax.swing.JFileChooser jfc = new javax.swing.JFileChooser();
//javax.swing.JFrame jf = new javax.swing.JFrame();
//jf.getContentPane().add(jfc);
//jf.show();
accessory = new LabelAccessory(jfc);
           jfc.setAccessory(accessory);
           jfc.addPropertyChangeListener(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY,accessory);

intt = jfc.showOpenDialog(this);
//jf.setSize(jfc.getSize());
//*/



            accessory = new LabelAccessory(jfc);
           jfc.setAccessory(accessory);
           jfc.addPropertyChangeListener(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY,accessory);








 
    while(fileSocketOut==null){
         
          try{
          try{
          this.fileSocketOut = new Socket(HOST,PORT);
          }catch(ConnectException conex1){;}//conex1.printStackTrace();}
          }catch(IOException io1){io1.printStackTrace();}
         

    }//end while
 
 

       try{
 
    in = new FileInputStream(fileToSend);
 
    bos = new BufferedOutputStream(fileSocketOut.getOutputStream());
   
    buff = new byte[BUFFER_SIZE];
 
    while((n=in.read(buff))!=-1){

        bos.write(buff,0,n);

    }//end while
 
       bos.flush();
       
       fileSocketOut.close();
 
       }catch(Exception objct){objct.printStackTrace();}
 

   }//end run
 
 

  public static void main (String args[]){

 
try{

      
    new UniversalFileSender(new File(args[0])).run();


}catch(ArrayIndexOutOfBoundsException aioobe){System.out.println("Supply the filename to be sent - ");System.exit(-1);}
  }
 

 public class LabelAccessory extends JLabel
           implements PropertyChangeListener {
     private static final int PREFERRED_WIDTH = 125;
     private static final int PREFERRED_HEIGHT = 100;

     public LabelAccessory(JFileChooser chooser) {
       setVerticalAlignment(JLabel.CENTER);
       setHorizontalAlignment(JLabel.CENTER);
       chooser.addPropertyChangeListener(this);
       setPreferredSize(new Dimension
               (PREFERRED_WIDTH, PREFERRED_HEIGHT));
     }  
     public void propertyChange(
       PropertyChangeEvent changeEvent) {
        String changeName =
          changeEvent.getPropertyName();
        if (changeName.equals
            (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
                File file = (File)changeEvent.getNewValue();
                if (file != null) {
                        ImageIcon icon =
                        new ImageIcon(file.getPath());
                if (icon.getIconWidth()
                    > PREFERRED_WIDTH) {
                        icon = new ImageIcon(
                        icon.getImage().getScaledInstance
                        (PREFERRED_WIDTH, -1,
                         Image.SCALE_DEFAULT));
                if (icon.getIconHeight()
                    > PREFERRED_HEIGHT) {
                        icon = new ImageIcon(
                        icon.getImage().getScaledInstance
                        (-1, PREFERRED_HEIGHT,
                         Image.SCALE_DEFAULT));
                }
          }
          setIcon(icon);
         }
       }
     }
   }






}
//---------------------------------------------------

0
 
LVL 16

Expert Comment

by:krakatoa
ID: 10655999

And here is what Sun themselves have to say about it:


Accessories
One of the more interesting aspects of JFileChooser is its accessory panel. This is an area of the chooser where you can place a component to coordinate information related to the current selection. For instance, if the current selection is an image type, the component can be an image previewer. For audio files, it could be a sound player. With each change in the file selection, different information is connected to the accessory panel.

To make an accessory panel, you create the appropriate component, attach the component to the JFileChooser with a call to setAccessory. The accessory panel attaches as a PropertyChangeListener to the JFileChooser. The specific property it needs to listen for is SELECTED_FILE_CHANGED_PROPERTY. When that property changes, the accessory component can change its state.

Here is an example. The following LabelAccessory can act as an image previewer:

   import javax.swing.*;
   import java.beans.*;
   import java.awt.*;
   import java.io.*;

   public class LabelAccessory extends JLabel
           implements PropertyChangeListener {
     private static final int PREFERRED_WIDTH = 125;
     private static final int PREFERRED_HEIGHT = 100;

     public LabelAccessory(JFileChooser chooser) {
       setVerticalAlignment(JLabel.CENTER);
       setHorizontalAlignment(JLabel.CENTER);
       chooser.addPropertyChangeListener(this);
       setPreferredSize(new Dimension
               (PREFERRED_WIDTH, PREFERRED_HEIGHT));
     }  
     public void propertyChange(
       PropertyChangeEvent changeEvent) {
        String changeName =
          changeEvent.getPropertyName();
        if (changeName.equals
            (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
                File file = (File)changeEvent.getNewValue();
                if (file != null) {
                        ImageIcon icon =
                        new ImageIcon(file.getPath());
                if (icon.getIconWidth()
                    > PREFERRED_WIDTH) {
                        icon = new ImageIcon(
                        icon.getImage().getScaledInstance
                        (PREFERRED_WIDTH, -1,
                         Image.SCALE_DEFAULT));
                if (icon.getIconHeight()
                    > PREFERRED_HEIGHT) {
                        icon = new ImageIcon(
                        icon.getImage().getScaledInstance
                        (-1, PREFERRED_HEIGHT,
                         Image.SCALE_DEFAULT));
                }
          }
          setIcon(icon);
         }
       }
     }
   }

To complete the process, run the following Accessories program. This gives you the accessory panel. When running the program, be sure to enter a directory with images in it. This will allow you to see the images in the preview panel. Notice that nothing appears in the preview panel if the current selection isn't an image.

   import java.io.File;
   import javax.swing.*;

   public class Accessories {

     public static void main(String args[]) {
       SwingUtilities.invokeLater(new Runnable() {
         public void run() {
           JFileChooser fileChooser =
                 new JFileChooser(".");
           LabelAccessory accessory =
                 new LabelAccessory(fileChooser);
           fileChooser.setAccessory(accessory);
           fileChooser.addPropertyChangeListener
               (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY,
                accessory);
           int status = fileChooser.showOpenDialog(null);
           if (status == JFileChooser.APPROVE_OPTION) {
             File selectedFile =
                    fileChooser.getSelectedFile();
             System.out.println("Selected: "
                    + selectedFile.getParent()
                    + " --- "
                    + selectedFile.getName());
           }
           System.exit(0);
         }
       });
     }
   }

0
 

Author Comment

by:Drop_of_Rain
ID: 10664147
I didn't get what some of the code krakatoa wrote with the filesocket. Can some one add some comments to that code as well please.


Hello everyone out there can someone help me

I already have the info from sun. That is not the problem I am having. In the code I included above, I have a runable filechooser to open an accessory panel in filechooser. There is a audio buttons to play clips and a textarea in the panel to write and read file descriptions. I need to get it to write  a sererate file with the same name as the selected file in filechooser(code included). I don't have a ProperyChangeEvent working with the textarea as well as other things. This is over my head and I need some help. Thanks in advance.
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:Drop_of_Rain
ID: 10668848
I agree with krakatoa,

no need to close the question. I just didn't get a response from him, and have found out the information sense then.

krakatoa.

Could you explain your code UniversalFileSender and how it has to do with what I asked. I'm new to this so everyone be patient with my lack of knowledge. Would you make comments in it as well please.
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 10669230
I posted that code because it includes the use of a FileChooser Accesory.

I then realised that might be too much, and so I just went to look for Sun's own example.

Since the implementation of accessories is generic, you should be able to extrapolate from how that one works, to add in other Accessories instead.

You may still have some problems with the audio side of things, but the main thrust of your question was about tackling accessories, so that's the reason. Perhaps, if you had said that audio was the main problem, I may not have come in.
0
 

Author Comment

by:Drop_of_Rain
ID: 10669736
Audio was not my main problem. It was really just smething simple I was just not seeing the problem.. I still don't get this code and what it has to do with accessory.

  while(fileSocketOut==null){
         
          try{
          try{
          this.fileSocketOut = new Socket(HOST,PORT);
          }catch(ConnectException conex1){;}//conex1.printStackTrace();}
          }catch(IOException io1){io1.printStackTrace();}
         

    }//end while
 
 

       try{
 
    in = new FileInputStream(fileToSend);
 
    bos = new BufferedOutputStream(fileSocketOut.getOutputStream());
   
    buff = new byte[BUFFER_SIZE];
 
    while((n=in.read(buff))!=-1){

        bos.write(buff,0,n);

    }//end while
 
       bos.flush();
       
       fileSocketOut.close();
 
       }catch(Exception objct){objct.printStackTrace();}
 

or

import java.io.*;
import java.net.*;
import java.beans.*;
import javax.swing.*;
import java.awt.*;



public class UniversalFileSender extends JFrame implements Runnable {
 
    private int n;

    private File fileToSend;
 
    private byte[] buff;
   
    private BufferedOutputStream bos;
    private FileInputStream in;
 
    private Socket fileSocketOut;

    private final static String HOST = "127.0.0.1";
    private final static int PORT = 30000;
    private final static int BUFFER_SIZE = 1024;
     
    LabelAccessory accessory;
 
     
public UniversalFileSender (File fileToSend){
 

   

    this.fileToSend = fileToSend;
   
please explain because I would llike to understand
0
 
LVL 16

Accepted Solution

by:
krakatoa earned 250 total points
ID: 10669806
Drop_of_Rain:

I already explained why all that code is there - did you not read my last comment?

Just ignore that block of code completely - it is for transferring a file over sockets.

Here is more:

CUSTOMIZING JFILECHOOSER
As is the case with all things in Swing, if you don't like the look of something, you can change it. In this tip, you'll learn how to customize the appearance of the JFileChooser component and its behavior. Let's start with a refresher on how to use the JFileChooser. Then let's examine single and multiple selection with the component, file and directory selection, setting up filters, adding accessories for previewing the currently selected content, and finally updating the file list view area.

Basic Usage
The JFileChooser component gives users a way to choose files and directories that they want to work with in the system. The component presents users with a dialog from which they can select one or more files and directories. Included with the JFileChooser component are a set of methods for showing a modal version of the dialog. Modal means that the methods don't return until the user selects something. These methods are showOpenDialog, showSaveDialog, and showDialog. The three methods control what text appears on the approval button (that is, what the user selects when he or she is finished with the dialog). There are also built-in methods for the common options Open and Save. The displayed file chooser dialog is appropriate for the current look and feel setting. This means that the dialog typically looks like the native file dialog for the user's platform, or the cross-platform Metal look and feel if none is specifically set.

The user selects something in the dialog and clicks the Open or Save button (or double-clicks the selection). The show methods then return a status, indicating whether the approval button was selected or the user closed the dialog without selecting anything (that is, the user clicked the Cancel button or the window adornment for closing). Possible return states are indicated by the class constants CANCEL_OPTION, APPROVE_OPTION, or ERROR_OPTION.

Here's a simple example that demonstrates JFileChooser.

   import java.io.File;
   import javax.swing.*;

   public class Basics {

     public static void main(String args[]) {
       SwingUtilities.invokeLater(new Runnable() {
         public void run() {
           JFileChooser fileChooser =
                  new JFileChooser(".");
           int status = fileChooser.showOpenDialog(null);
           if (status == JFileChooser.APPROVE_OPTION) {
             File selectedFile =
                  fileChooser.getSelectedFile();
             System.out.println("Selected: "
                    + selectedFile.getParent()
                    + " --- "
                    + selectedFile.getName());
           }
           System.exit(0);
         }
       });
     }
   }

The program displays a file chooser dialog. After the user selects a directory and file, the dialog identifies the directory and displays the filename.

 

Single and Multiple Selection
By default, the JFileChooser starts in single-selection mode. This means that a user can select only one directory or file at a time. If you want to allow the user to select multiple items at a time, you need to set the multiSelectionEnabled property to true. Here's an example:

   import java.io.File;
   import javax.swing.*;

   public class Multi {

     public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            JFileChooser fileChooser
                   = new JFileChooser(".");
            fileChooser.setMultiSelectionEnabled(true);
            int status = fileChooser.showOpenDialog(null);
            if (status == JFileChooser.APPROVE_OPTION) {
                   File selectedFiles[] =
                        fileChooser.getSelectedFiles();
               for (int i=0,
                    n=selectedFiles.length; i<n; i++) {
                         System.out.println("Selected: "
                         + selectedFiles[i].getParent()
                         + " --- "
                         + selectedFiles[i].getName());
               }
            }
            System.exit(0);
          }
       });
     }
   }

Notice that this uses getSelectedFiles() not getSelectedFile() to retrieve the selection set.

 

Prior to J2SE SDK version 1.4, there were issues about which look and feels supported multiple selection. Currently, all the system-provided look and feels support the behavior.

File and Directory Selection
Although a user typically selects files with the file chooser, you can also allow a user to select directories. You do this with a simple call to the setFileSelectionMode method. In making the call, you specify one of the following constants:

JFileChooser.FILES_ONLY
JFileChooser.DIRECTORIES_ONLY
JFileChooser.FILES_AND_DIRECTORIES
Each of the constants specifies a mode for the file chooser. For example, the JFileChooser.FILES_AND_DIRECTORIES constant sets the file chooser to allow both file and directory selection (in other words, a user can select files and directories from the same chooser).

You can combine multiple selection with directory selection. This enables a user to select multiple directories in one chooser. This is shown in the following program.

   import java.io.File;
   import javax.swing.*;

   public class Dirs {

     public static void main(String args[]) {
       SwingUtilities.invokeLater(new Runnable() {
         public void run() {
           JFileChooser fileChooser =
                  new JFileChooser(".");
           fileChooser.setMultiSelectionEnabled(true);
           fileChooser.setFileSelectionMode(
                  JFileChooser.DIRECTORIES_ONLY);
           int status = fileChooser.showOpenDialog(null);
           if (status == JFileChooser.APPROVE_OPTION) {
             File selectedFiles[] =
                 fileChooser.getSelectedFiles();
             for
               (int i=0, n=selectedFiles.length; i<n; i++) {
                     System.out.println("Selected: "
                        + selectedFiles[i].getParent()
                        + " --- "
                        + selectedFiles[i].getName());
             }
           }
           System.exit(0);
         }
       });
     }
   }

 

In directory selection mode, the initial text in the File Name area is the currently selected directory. In file selection mode, the field is empty.

File Filters
File filters (or input masks) allow you to limit which files can be selected in the chooser. For instance, if you only want a user to see .java source files, you can configure a file filter (a subclass of the FileFilter class) for only that file extension. The default file filter is "accept all" (which lists everything in the file chooser). When you add a file filter to the chooser, the filter appears in the appropriate drop-down list. For the Motif version of the chooser, this is above the Folders list. For the Windows and Metal versions, this is at the window bottom.

To add file filters to the file chooser, you need to create a FileFilter instance from the javax.swing.filechooser package. You then call the addChooseableFileFilter method, passing in the new filter. The filter is then available from the drop-down list of filters. You can also select the filter by calling the setFileFilter method. That way, when the chooser is initially displayed, you can have a filter set besides the 'all' one. If you don't explicitly set a file filter, the last one added is the initial selection.

It's important to not confuse the file filter for JFileChooser with the filter in the Java I/O package. Although the names are identical, their packages and usage are not.

Shown below is a program named Filters that demonstrates the use of file filters. To run the program, you need to get the ExampleFileFilter class that comes with the SDK demos. Look in the demo/jfc/FileChooserDemo/src (of course, reverse the slashes for Windows) directory of the SDK. The ExampleFileFilter class lets you create filters for any set of extensions. This makes it simple to install filters. Just add the appropriate file extensions, and add each filter to the chooser.

   import java.io.File;
   import javax.swing.*;

   public class Filters {

     public static void main(String args[]) {
       SwingUtilities.invokeLater(new Runnable() {
         public void run() {
           JFileChooser fileChooser =
                  new JFileChooser(".");
           ExampleFileFilter filter =
                  new ExampleFileFilter("java");
           filter.setDescription("Java Source Files");
           fileChooser.addChoosableFileFilter(filter);

           filter = new ExampleFileFilter("class");
           filter.setDescription("Class Files");
           fileChooser.addChoosableFileFilter(filter);

           filter = new ExampleFileFilter("java");
           filter.addExtension("class");
           filter.setDescription("Source and Class Files");
           fileChooser.addChoosableFileFilter(filter);

           int status = fileChooser.showOpenDialog(null);
           if (status == JFileChooser.APPROVE_OPTION) {
             File selectedFile =
                    fileChooser.getSelectedFile();
             System.out.println("Selected: "
                    + selectedFile.getParent()
                    + " --- "
                    + selectedFile.getName());
           }
           System.exit(0);
         }
       });
     }
   }

 

Accessories
One of the more interesting aspects of JFileChooser is its accessory panel. This is an area of the chooser where you can place a component to coordinate information related to the current selection. For instance, if the current selection is an image type, the component can be an image previewer. For audio files, it could be a sound player. With each change in the file selection, different information is connected to the accessory panel.

To make an accessory panel, you create the appropriate component, attach the component to the JFileChooser with a call to setAccessory. The accessory panel attaches as a PropertyChangeListener to the JFileChooser. The specific property it needs to listen for is SELECTED_FILE_CHANGED_PROPERTY. When that property changes, the accessory component can change its state.

Here is an example. The following LabelAccessory can act as an image previewer:

   import javax.swing.*;
   import java.beans.*;
   import java.awt.*;
   import java.io.*;

   public class LabelAccessory extends JLabel
           implements PropertyChangeListener {
     private static final int PREFERRED_WIDTH = 125;
     private static final int PREFERRED_HEIGHT = 100;

     public LabelAccessory(JFileChooser chooser) {
       setVerticalAlignment(JLabel.CENTER);
       setHorizontalAlignment(JLabel.CENTER);
       chooser.addPropertyChangeListener(this);
       setPreferredSize(new Dimension
               (PREFERRED_WIDTH, PREFERRED_HEIGHT));
     }  
     public void propertyChange(
       PropertyChangeEvent changeEvent) {
        String changeName =
          changeEvent.getPropertyName();
        if (changeName.equals
            (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
                File file = (File)changeEvent.getNewValue();
                if (file != null) {
                        ImageIcon icon =
                        new ImageIcon(file.getPath());
                if (icon.getIconWidth()
                    > PREFERRED_WIDTH) {
                        icon = new ImageIcon(
                        icon.getImage().getScaledInstance
                        (PREFERRED_WIDTH, -1,
                         Image.SCALE_DEFAULT));
                if (icon.getIconHeight()
                    > PREFERRED_HEIGHT) {
                        icon = new ImageIcon(
                        icon.getImage().getScaledInstance
                        (-1, PREFERRED_HEIGHT,
                         Image.SCALE_DEFAULT));
                }
          }
          setIcon(icon);
         }
       }
     }
   }

To complete the process, run the following Accessories program. This gives you the accessory panel. When running the program, be sure to enter a directory with images in it. This will allow you to see the images in the preview panel. Notice that nothing appears in the preview panel if the current selection isn't an image.

   import java.io.File;
   import javax.swing.*;

   public class Accessories {

     public static void main(String args[]) {
       SwingUtilities.invokeLater(new Runnable() {
         public void run() {
           JFileChooser fileChooser =
                 new JFileChooser(".");
           LabelAccessory accessory =
                 new LabelAccessory(fileChooser);
           fileChooser.setAccessory(accessory);
           fileChooser.addPropertyChangeListener
               (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY,
                accessory);
           int status = fileChooser.showOpenDialog(null);
           if (status == JFileChooser.APPROVE_OPTION) {
             File selectedFile =
                    fileChooser.getSelectedFile();
             System.out.println("Selected: "
                    + selectedFile.getParent()
                    + " --- "
                    + selectedFile.getName());
           }
           System.exit(0);
         }
       });
     }
   }

 

FileView
The area in a file chooser where the filenames are listed is controlled by the abstract FileView class. You can customize how the files are listed by creating a custom subclass. The class has five methods for getting things like icon and name, however you don't have to customize the behavior for everything. When one of the methods returns null, the component examines the look-and-feel specific behavior to get the default value.

To demonstrate, let's create a JFileChooser that shows special icons for Java-related files: a blue icon for .java files, and a green icon for .class files. In addition, for .java files, let's append the file size to the file name.

Here is the definition of the icon:

   import javax.swing.*;
   import java.awt.*;
   
   public class DiamondIcon implements Icon {
     private Color color;
     private boolean selected;
     private int width;
     private int height;
     private Polygon poly;
     private static final int DEFAULT_WIDTH = 10;
     private static final int DEFAULT_HEIGHT = 10;
     public DiamondIcon(Color color) {
             this(color, true, DEFAULT_WIDTH,
                  DEFAULT_HEIGHT);
     }
     public DiamondIcon(Color color, boolean selected) {
             this(color, selected, DEFAULT_WIDTH,
                  DEFAULT_HEIGHT);
     }
     public DiamondIcon(Color color, boolean selected,
                        int width, int height) {
       this.color = color;
       this.selected = selected;
       this.width = width;
       this.height = height;
       initPolygon();
     }
     private void initPolygon() {
       poly = new Polygon();
       int halfWidth = width/2;
       int halfHeight = height/2;
       poly.addPoint(0, halfHeight);
       poly.addPoint(halfWidth, 0);
       poly.addPoint(width, halfHeight);
       poly.addPoint(halfWidth, height);
     }
     public int getIconHeight() {
       return height;
     }
     public int getIconWidth() {
       return width;
     }
     public void paintIcon(
      Component c, Graphics g, int x, int y) {
       g.setColor(color);
       g.translate(x, y);
       if (selected) {
         g.fillPolygon(poly);
       } else {
         g.drawPolygon(poly);
       }
       g.translate(-x, -y);
     }
   }

Here is the program that creates the JFileChooser that shows the special icons. If you like, you can comment out the setFileView line to see the default behavior. Then you could add it back to see the customized FileView with the blue and green icons (this assumes that you are in a directory that contains the source and compiled source files).

   import java.io.File;
   import java.awt.*;
   import javax.swing.*;
   import javax.swing.filechooser.*;

   public class JavaFileView extends FileView {
     Icon javaIcon = new DiamondIcon(Color.blue);
     Icon classIcon = new DiamondIcon(Color.green);

     /**
      * If .java file, add length to name
      */
     public String getName(File file) {
       String filename = file.getName();
       if (filename.endsWith(".java")) {
               filename += " : " + file.length();
               return filename;
       }
       return null;
     }

     /**
      * Return special icons for .java and .class files
      */
     public Icon getIcon(File file) {
       // default icons for all directories
       if (file.isDirectory()) {
               return null;
       }
       String filename = file.getName();
       if (filename.endsWith(".java")) {
               return javaIcon;
       } else if (filename.endsWith(".class")) {
         return classIcon;
     }
     return null;
     }

     public static void main(String args[]) {
       SwingUtilities.invokeLater(new Runnable() {
         public void run() {
           JFileChooser fileChooser =
                  new JFileChooser(".");
           FileView view = new JavaFileView();
           fileChooser.setFileView(view);
           int status = fileChooser.showOpenDialog(null);
           System.exit(0);
         }
       });
     }
   }

 

For more information about JFileChooser "see the javadoc". Also, see "How to Use File Choosers" in the The Java Tutorial. For more information about multithreading and Swing, see "How to Use Threads" in the Java Tutorial.


0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now