Previewing textfiles in a JFileChooser

Use the setAccessory method!

Main.java:

import javax.swing.filechooser.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.awt.*;
import java.io.*;
  
public class Main extends JFrame {
   public static void main(String[] args) {
      JFileChooser fc = new JFileChooser();
 
      // show only directories and .txt files       
      fc.addChoosableFileFilter(new TextfileFilter());
 
      // set the accessory JComponent to our panel that previews textfiles
      fc.setAccessory(new TextfilePreview(fc));
 
      int returnVal = fc.showDialog(new JFrame(), "Open");
 
      if (returnVal == JFileChooser.APPROVE_OPTION) {
         File file = fc.getSelectedFile();
      }
 
      System.exit(0);
   }
}
 
class TextfileFilter extends javax.swing.filechooser.FileFilter
{
   public boolean accept(File f) {
      if (f.isDirectory()) return true;
 
      return f.getName().toLowerCase().endsWith(".txt");
   }
 
   public String getDescription() {
      return "TextFiles (*.txt)";
   }
}
 
class TextfilePreview extends JPanel
                      implements PropertyChangeListener {
   File textfile;
   JTextArea ta;
 
   public TextfilePreview(JFileChooser fc) {
      fc.addPropertyChangeListener(this);
      ta = new JTextArea();
      JScrollPane sp = new JScrollPane(ta);
      setLayout(new BorderLayout());
      add(BorderLayout.CENTER, sp);
      setPreferredSize(new Dimension(150, 200));
   }
 
   public void loadTextfile() {
      if (textfile == null) return;
 
      try {
         ta.setText("");
         BufferedReader br = new BufferedReader(new FileReader(textfile));
         String line;
         while ((line = br.readLine()) != null) {
            ta.append(line + "n");
         }
         br.close();
      }
      catch(IOException e) {
      }
   } 
 
   public void propertyChange(PropertyChangeEvent e) {
      String prop = e.getPropertyName();
      if (prop.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
         textfile = (File) e.getNewValue();
         if (isShowing()) {
            loadTextfile();
            repaint();
         }
      }
   }
}