简体   繁体   English

文件筛选器未出现在Java swing中的JFileChooser上

[英]File Filter does not appear on JFileChooser in Java swing

I have a JButton that needs to open a file of a specific extension. 我有一个JButton,需要打开特定扩展名的文件。 In brief, I define a JButton add an actionlistener to it that fires a JFileChooser, if JButton is clicked. 简而言之,我定义了一个JButton,如果单击JButton,则向其添加一个动作侦听器,该动作侦听器将触发JFileChooser。 I want to add a file filter so that only files of extension .mpg will be shown on the JFileChooser. 我想添加一个文件过滤器,以便仅扩展名.mpg的文件将显示在JFileChooser上。

The compilation shows no errors, but on the swing the JFileChooser shows no filtering of the available files (nor the option 'Movie files' in the combobox appears - just 'All files'). 编译没有显示任何错误,但是JFileChooser在显示时没有显示对可用文件的过滤(组合框中的“电影文件”选项也不会出现-仅是“所有文件”)。 In two words, it seems that addChoosableFileFilter has no effect whatsoever. 用两个词来说, addChoosableFileFilter似乎没有任何作用。

My code is: 我的代码是:

final JFileChooser jfc = new JFileChooser(moviedir);
//add File Filter
jfc.addChoosableFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "Movie files (*.mpg)";
}
@Override
public boolean accept(File f) {
if (f.isDirectory()) {return true;} 
else {return f.getName().toLowerCase().endsWith(".mpg");}
 }
});

I have also tried the alternative of 我也尝试过

jfc.addChoosableFileFilter(new FileNameExtensionFilter("Movie files", "mpg"));

with the same fate. 命运一样 All the above are on JPanel of a JFrame of my swing. 以上所有内容都在我的JFrame的JPanel上。

I 've read many related threads but no luck. 我读过许多相关主题,但没有运气。

Thanks in advance for comments. 预先感谢您的评论。

JFileChooser provides a simple mechanism for the user to choose a file. JFileChooser为用户提供了一种选择文件的简单机制。 For information about using JFileChooser, see How to Use File Choosers, a section in The Java Tutorial. 有关使用JFileChooser的信息,请参阅《 Java教程》中的“如何使用文件选择器”。

The following code pops up a file chooser for the user's home directory that sees only .jpg and .gif images: 以下代码弹出用户主目录的文件选择器,该文件选择器仅显示.jpg和.gif图像:

JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
    "JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
   System.out.println("You chose to open this file: " +
        chooser.getSelectedFile().getName());
}

Try this. 尝试这个。 Copied from here 从这里复制

Try this code. 试试这个代码。 It worked for me 对我有用

call your filechooser like this:- 像这样调用您的文件选择器:

JFileChooser fc = new JFileChooser("C:/");
            fc.setFileFilter(new JPEGImageFileFilter());

and make class JPEGImageFileFilter like this:- 使类JPEGImageFileFilter像这样:

 class JPEGImageFileFilter extends FileFilter implements java.io.FileFilter
         {
         public boolean accept(File f)
           {
           if (f.getName().toLowerCase().endsWith(".jpeg")) return true;
           if (f.getName().toLowerCase().endsWith(".jpg")) return true;
           if (f.getName().toLowerCase().endsWith(".avi")) return true;
           if (f.getName().toLowerCase().endsWith(".mpeg")) return true;
           return false;
           }
         public String getDescription()
           {
           return "JPEG files";
           }

         }

Just provide an example for reference. 请提供一个示例以供参考。

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;

import java.text.*;

public class TextReaderExapmle extends JFrame {

    private static final long serialVersionUID = -8816650884305666302L;
    private static final String FRAME_TITLE = "File Chosser demo";
    private static final Dimension FRAME_SIZE = new Dimension(400, 350);
    private JButton fileChoosingButton;
    private JTextArea textArea;
    private JFileChooser fileChooser;

    public TextReaderExapmle() {
        super(FRAME_TITLE);
        init();
        doLay();
        attachListeners();
    }

    private void init() {
        fileChoosingButton = new JButton(new FileChooseAction());
        textArea = new JTextArea();

        fileChooser = new JFileChooser(System.getProperty("user.dir"));
        fileChooser.setFileFilter(new TextFileFilter());
        fileChooser.setMultiSelectionEnabled(false);
    }

    private void doLay() {
        Container container = getContentPane();
        container.add(fileChoosingButton, BorderLayout.NORTH);
        container.add(new JScrollPane(textArea), BorderLayout.CENTER);

        setSize(FRAME_SIZE);
        setVisible(true);
    }

    private void attachListeners() {
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(1);
            }
        });
    }

    /**
     * read text from the selected text file and convert text to string
     * 
     * @param reader
     * @return converted string
     */
    private static String readTextFromFile(final FileReader reader) {
        if (reader == null)
            return "";
        StringBuffer buf = new StringBuffer();

        final int CACHE_SIZE = 1024;
        final char[] cache = new char[CACHE_SIZE];
        try {
            int b;
            while ((b = reader.read(cache)) != -1) {
                if (b < CACHE_SIZE)
                    buf.append(cache, 0, b);
                else
                    buf.append(cache);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buf.toString();
    }

    /**
     * open file chooser action
     */
    private class FileChooseAction extends AbstractAction {
        static private final String ACTION_LABEL = "Open File...";

        public FileChooseAction() {
            super(ACTION_LABEL);
        }

        public void actionPerformed(ActionEvent e) {

            int returnVal = fileChooser.showOpenDialog(fileChoosingButton);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                try {
                    FileReader reader = new FileReader(
                            fileChooser.getSelectedFile());
                    textArea.setText(readTextFromFile(reader));
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /* file filter */
    private class TextFileFilter extends FileFilter {
        private final java.util.List<String> fileNameExtensionList = new ArrayList<String>();

        public TextFileFilter() {
            fileNameExtensionList.add("txt");
            fileNameExtensionList.add("java");
            fileNameExtensionList.add("log");
            fileNameExtensionList.add("xml");
            fileNameExtensionList.add("htm");
            fileNameExtensionList.add("html");
            fileNameExtensionList.add("html");
            fileNameExtensionList.add("properties");
            fileNameExtensionList.add("svg");
        }

        public boolean accept(File f) {
            if (f.isDirectory())
                return true;
            final String fileName = f.getName();
            int lastIndexOfDot = fileName.lastIndexOf('.');

            if (lastIndexOfDot == -1)
                return false;

            int fileNameLength = fileName.length();
            final String extension = fileName.substring(lastIndexOfDot + 1,
                    fileNameLength);

            return fileNameExtensionList.contains(extension);
        }

        public String getDescription() {
            StringBuffer buf = new StringBuffer("Text File(");
            for (String fn : fileNameExtensionList)
                buf.append(MessageFormat.format("*.{0};", fn));
            return buf.append(')').toString();
        }
    }

    public static void main(String[] args) {
        new TextReaderExapmle();
    }
}

简单...

jfc.setFileFilter(new FileNameExtensionFilter("Movie files", "mpg"));

use following code and make it more readable and easy: 使用以下代码,使其更具可读性和易用性:

final JFileChooser jfc = new JFileChooser(moviedir); 最终的JFileChooser jfc =新的JFileChooser(moviedir);

jfc.addChoosableFileFilter(new FileNameExtensionFilter("*.mpg", "mpg")); jfc.addChoosableFileFilter(new FileNameExtensionFilter(“ *。mpg”,“ mpg”));;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM