我需要在仅允许选择图像文件的文件选择器中过滤文件。我似乎无法在这里弄清楚我的代码出了什么问题:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.ImageFilter;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;


public class Viewer extends JFrame implements ActionListener{
 /**
  *
  */
 private static final long serialVersionUID = 1L;

 private JMenuItem open;
 private JMenuItem exit;
 private JFileChooser fileChooser;
 private JLabel image;

 public Viewer(){
  super("Picture Viewer");
  this.setLayout(new BorderLayout());
  //this.setSize(400, 400);

  JPanel canvas = new JPanel();
  this.add(canvas, BorderLayout.CENTER);
  image = new JLabel();
  canvas.add(image, BorderLayout.CENTER);

  JMenuBar menubar = new JMenuBar();
  this.add(menubar, BorderLayout.NORTH);
  JMenu menu = new JMenu("File");
  menubar.add(menu);
  open = new JMenuItem("Open...");
  open.addActionListener(this);
  menu.add(open);
  exit = new JMenuItem("Exit");
  exit.addActionListener(this);
  menu.add(exit);

  this.setVisible(true);
  this.pack();
 }

 public void actionPerformed(ActionEvent e){
  if(e.getSource() == open){
   fileChooser = new JFileChooser();
   fileChooser.showOpenDialog(this);
   fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
   fileChooser.setFileFilter(new ImageFileFilter());

    int returnVal = fileChooser.showOpenDialog(null);
          if(returnVal == JFileChooser.APPROVE_OPTION) {
              File file = fileChooser.getSelectedFile();
              // bmp, gif, jpg, png files okay
              BufferedImage bi;
     try {
      bi = ImageIO.read(file);
               image.setIcon(new ImageIcon(bi));
     } catch (IOException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
     }
              // catch IOException
          }
      this.pack();
  }
  else if(e.getSource() == exit){
   System.exit(0);
  }
 }

 public static void main(String[] args){
  Viewer viewer = new Viewer();
 }
 public class ImageFileFilter implements FileFilter{
   private final String[] okFileExtensions =
     new String[] {"jpg", "png", "gif", "bmp"};

   public boolean accept(File file)
   {
     for (String extension : okFileExtensions)
     {
       if (file.getName().toLowerCase().endsWith(extension))
       {
         return true;
       }
     }
     return false;
   }
 }
}

告诉我,实现FileFilter的自定义过滤器类不是FileFilter类型。 :/

最佳答案

JFileChooser需要您扩展javax.swing.filechooser.FileFilter的实例。由于您具有实现,因此您的IDE会改为导入java.io.FileFilter

09-27 12:45