JFileChooser и затмение

Я ищу способ, чтобы JFileChooser позволял пользователю выбирать из текстовых файлов, которые включены только в файл bin проекта eclipse. Есть ли способ, чтобы всплывающее окно JFileChooser отображало выбранное количество файлов txt, которые находятся в папке bin?


person M_x_r    schedule 06.12.2012    source источник
comment
вы запускаете приложение из Eclipse, jar или обоих?   -  person Nikolay Kuznetsov    schedule 06.12.2012
comment
Будет ли пользователь запускать ваше приложение из Eclipse? Если нет, то ваш вопрос бессмыслен.   -  person Guillaume Polet    schedule 06.12.2012
comment
@GuillaumePolet, я согласен. Относительный путь имеет смысл только для запуска из Eclipse. В противном случае вам нужно использовать абсолютный путь, но тогда то, что вы пытаетесь сделать, непонятно.   -  person Nikolay Kuznetsov    schedule 06.12.2012
comment
Да, они будут запускать демо из eclipse   -  person M_x_r    schedule 06.12.2012
comment
Это должно быть просто сделать. Например, вы можете дать объекту чтения файлов строку с именем файла txt, и eclipse сможет ее найти. Итак, теперь я просто хочу найти способ создать каталог, который указывает на папку привязки и просто подбирает файлы txt.   -  person M_x_r    schedule 06.12.2012


Ответы (3)


Вы можете обратиться к следующему коду, просто укажите абсолютный или относительный путь к вашей папке/каталогу

JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
    "TXT files", "txt");
chooser.setFileFilter(filter);
chooser.setCurrentDirectory("<YOUR DIR COMES HERE>");
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
   System.out.println("You chose to open this file: " +
        chooser.getSelectedFile().getName());
}

JFileChooser

person Nikolay Kuznetsov    schedule 06.12.2012
comment
@Nicolay Kuznetsov Привет .. Спасибо за это ... но есть ли способ указать только на txt-файлы, которые находятся в папке eclipse bin данного проекта ?? - person M_x_r; 06.12.2012
comment
Спасибо, но я пытаюсь понять, как установить относительный путь, чтобы у разных людей, использующих приложение, были только те файлы txt, которые я установил на выбор. - person M_x_r; 06.12.2012
comment
Я не понимаю, почему людям из приложения нужно видеть список txt-файлов в несвязанном проекте eclipse. Пожалуйста, обновите вопрос со структурой проекта Eclipse и тем, как вы запускаете приложение. Если вы запускаете его из JAR, это должен быть абсолютный путь. - person Nikolay Kuznetsov; 06.12.2012

Итак, вы хотите отображать только определенные текстовые файлы в каталоге?

Используйте FileFilter, который будет сравнивать имя файла с ArrayList именами файлов, если совпадение будет найдено, он вернет true, что позволит JFileChooser показать файл

Что-то типа:

JFileChooser fc=..;
fc.setCurrentDirectory(new File("path/to/bin/"));//put path to bin here

 ....     

 ArrayList<String> filesToSee=new ArrayList<>();
 //add names of files we want to be visible to user of JFileChooser
 filesToSee.add("file1.txt");
 filesToSee.add("file2.txt");

fc.addChoosableFileFilter(new MyFileFilter(filesToSee));

//By default, the list of user-choosable filters includes the Accept All filter, which        enables the user to see all non-hidden files. This example uses the following code to disable the Accept All filter:
fc.setAcceptAllFileFilterUsed(false);

....

class MyFileFilter extends FileFilter {

     private ArrayList<String> files;

     public MyFileFilter(ArrayList<String> files) {
         this.files=files;
     }

    //Accept only files in passed array
    public boolean accept(File f) {

        for(String s:files) {
            if(f.getName().equals(s)) {
                return true;
             }
        }

        return false;
    }

    //The description of this filter
    public String getDescription() {
        return "Specific Files";
    }
}

Ссылка:

person David Kroukamp    schedule 06.12.2012

Другой способ сделать это - реализовать FileSystemView, чтобы он отображал только ваш каталог и не позволял подниматься выше в иерархии или других «дисках».

Вот демонстрация такого FileSystemView. Все, что вам нужно указать на входе, это корневой каталог (то есть путь к вашей корзине, возможно, что-то вроде new File("bin"), если рабочий каталог считается корнем вашего проекта Eclipse, что Eclipse делает по умолчанию).

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileSystemView;

public class TestJFileChooser2 {

    public static class MyFileSystemView extends FileSystemView {

        private File root;

        public MyFileSystemView(File root) {
            super();
            try {
                this.root = root.getCanonicalFile();
            } catch (IOException e) {
                this.root = root;
            }
        }

        @Override
        public File[] getRoots() {
            return new File[] { root };
        }

        @Override
        public File createNewFolder(File containingDir) throws IOException {
            return FileSystemView.getFileSystemView().createNewFolder(containingDir);
        }

        @Override
        public File createFileObject(String path) {
            File file = super.createFileObject(path);
            if (isEmbedded(file)) {
                return file;
            } else {
                return root;
            }
        }

        @Override
        public File createFileObject(File dir, String filename) {
            if (isEmbedded(dir)) {
                return super.createFileObject(dir, filename);
            } else {
                return root;
            }

        }

        @Override
        public File getDefaultDirectory() {
            return root;
        }

        private boolean isEmbedded(File file) {
            while (file != null && !file.equals(root)) {
                file = file.getParentFile();
            }
            return file != null;
        }

        @Override
        public File getParentDirectory(File dir) {
            File parent = dir.getParentFile();
            if (isEmbedded(parent)) {
                return parent;
            } else {
                return root;
            }
        }
    }

    protected void initUI() {
        JFrame frame = new JFrame("Test file chooser");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JButton ok = new JButton("Click me to select file");
        ok.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        final JFileChooser openFC = new JFileChooser(new MyFileSystemView(new File("")));
                        openFC.setDialogType(JFileChooser.OPEN_DIALOG);
                        // Configure some more here
                        openFC.showDialog(ok, null);
                    }
                });
            }
        });
        frame.add(ok);
        frame.setBounds(100, 100, 300, 200);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedLookAndFeelException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {

                new TestJFileChooser2().initUI();
            }
        });
    }
}
person Guillaume Polet    schedule 06.12.2012