1

JList使用. JFileChooser_ vector我试图通过检查特定文件是否可用来系统地完成它JList。例如,如果我添加一个名为“abc.xml”的文件,我会立即检查该文件是否存在JList

另外我想检查文件是否只重复一次。如果重复多次('abc.xml', 'abc.xml',...),应该有错误信息表明文件被多次添加。

我在这里发布我的完整代码;

         public Test() 
{
    setTitle("EXAMPLE");
    getContentPane().setLayout(new MigLayout("", "[][][][][grow][][][][][][][]
               [][][grow][grow][][][grow][][][][][][][grow]", "[][][][][][][][grow]
              [grow][][][][][][][grow][]"));

    final JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    fileChooser.setMultiSelectionEnabled(true);
    getContentPane().add(fileChooser, "cell 0 1 3 16");

    JScrollPane scrollPane = new JScrollPane();
    getContentPane().add(scrollPane, "cell 23 2 3 15,grow");

    vector = new Vector<File>();
    final JList list = new JList(vector);
    scrollPane.setViewportView(list);


    JButton btnNewButton = new JButton(" Add          ");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            for (File file : fileChooser.getSelectedFiles()) {
                        vector.addElement(file);
                 }
                //System.out.println("Added..!!");
                list.updateUI();

            }
    });
    getContentPane().add(btnNewButton, "cell 4 0");



    JButton btnNewButton_1 = new JButton(" Remove   ");
    btnNewButton_1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if(list.getSelectedIndices().length > 0) {
                  int[] selectedIndices = list.getSelectedIndices();
                  for (int i = selectedIndices.length-1; i >=0; i--) {
                        vector.removeElementAt(i);
                    } 
                   }
                    //System.out.println("Removed..!!");
                    list.updateUI();

        }   
        });
    getContentPane().add(btnNewButton_1, "cell 4 2");

    JButton btnNewButton_2 = new JButton(" Check       ");
    btnNewButton_2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            ***File file = fileChooser.getSelectedFile();
            boolean found = false;
            for (File f : vector) {
                 if (file.getName().equals(f.getName())) {
                     found = true;
                     break;
                 }
            }
            if (!found) {
                vector.add(file);
                fireIntervalAdded(this, vector.size()-1, vector.size()-1);
            } else {
                // Abusive usage of an exception
                JOptionPane.showMessageDialog(null, "File " + file.getName() + " 
                already added");

            }***
         });

           public static void main(String args[]) {        
          // Create an instance of the test application         
           Test mainFrame = new Test();        
           mainFrame.pack();         
           mainFrame.setVisible(true);     
  }

我得到的是,一个消息框告诉即使文件只出现一次,文件也已添加。

我期望的是,当文件被添加一次时,它不应该显示任何东西。但是当它被添加不止一次时,它才应该显示一个文件已经添加的消息。

有人可以帮忙吗?

4

2 回答 2

3

好的,这是您描述的示例。我不太确定拒绝添加文件的条件是什么。这是基于名称的,但我想知道您是否不是在寻找File.equals()using first getCanonicalFile()。我也在代码的注释中展示了这一点。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Vector;

import javax.swing.AbstractListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class Test {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                initUI();
            }
        });
    }

    public static class MyListModel extends AbstractListModel {

        private Vector<File> files = new Vector<File>();

        public void addFilesToModel(File[] f) {
            for (File file : f) {
                addFileToModel(file);
            }
        }

        public void addFileToModel(File file) throws IllegalArgumentException {
            boolean found = false;
            // file = file.getCanonicalFile();
            for (File file2 : files) {
                // file2.getCanonicalFile().equals(file) + throw IOException
                if (file2.getName().equals(file.getName())) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                files.add(file);
                fireIntervalAdded(this, files.size() - 1, files.size() - 1);
            } else {
                // Abusive usage of an exception
                throw new IllegalArgumentException("File " + file.getName() + " already added");
            }
        }

        @Override
        public int getSize() {
            return files.size();
        }

        @Override
        public Object getElementAt(int index) {
            return files.get(index);
        }

    }

    private static File lastFolder;

    protected static void initUI() {
        JFrame frame = new JFrame("test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        final MyListModel model = new MyListModel();
        JList list = new JList(model);
        final JButton button = new JButton("Add files...");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser chooser = new JFileChooser();
                if (lastFolder != null) {
                    chooser.setCurrentDirectory(lastFolder);
                }
                chooser.setMultiSelectionEnabled(true);
                chooser.showDialog(button, "Add files");
                if (chooser.getSelectedFiles() != null) {
                    for (File file : chooser.getSelectedFiles()) {
                        try {
                            model.addFileToModel(file);
                        } catch (IllegalArgumentException e1) {
                            JOptionPane.showMessageDialog(button, e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                    lastFolder = chooser.getCurrentDirectory();
                }
            }
        });
        panel.add(new JScrollPane(list));
        panel.add(button);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}

编辑


除了您的代码不完整这一事实之外,我还设法对其进行了安排并使其工作,但它确实远非完美。我也摆脱了 MigLayout,因为它需要一个额外的库。随意放回去。

import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Vector;

import javax.swing.AbstractListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class Test extends JFrame {

    Vector<File> vector;
    JPanel root;
    private MyListModel model;

    public class MyListModel extends AbstractListModel {

        public void addFilesToModel(File[] f) {
            for (File file : f) {
                addFileToModel(file);
            }
        }

        public void addFileToModel(File file) throws IllegalArgumentException {
            boolean found = false;
            // file = file.getCanonicalFile();
            for (File file2 : vector) {
                // file2.getCanonicalFile().equals(file) + throw IOException
                if (file2.getName().equals(file.getName())) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                vector.add(file);
                fireIntervalAdded(this, vector.size() - 1, vector.size() - 1);
            } else {
                // Abusive usage of an exception
                throw new IllegalArgumentException("File " + file.getName() + " already added");
            }
        }

        public void removeFileFromModel(File file) throws IllegalArgumentException {
            int index = vector.indexOf(file);
            File removed = vector.remove(index);
            if (removed != null) {
                fireIntervalRemoved(this, index, index);
            } else {
                // Nothing was removed
            }
        }

        public void removeFilesFromModel(File[] files) {
            for (File f : files) {
                removeFileFromModel(f);
            }
        }

        @Override
        public int getSize() {
            return vector.size();
        }

        @Override
        public Object getElementAt(int index) {
            return vector.get(index);
        }

    }

    public Test() {
        super("EXAMPLE");
        root = new JPanel(new GridBagLayout());
        vector = new Vector<File>();
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridheight = 2;
        getContentPane().add(root);
        final JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        fileChooser.setMultiSelectionEnabled(true);
        root.add(fileChooser, gbc);
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.ipadx = 5;
        gbc.ipady = 5;
        gbc.gridheight = 1;
        gbc.gridwidth = 3;
        gbc.gridx = 1;

        vector = new Vector<File>();
        model = new MyListModel();
        final JList list = new JList(model);
        JScrollPane scrollPane = new JScrollPane(list);
        root.add(scrollPane, gbc);
        gbc.gridwidth = 1;
        gbc.weightx = 0;
        gbc.weighty = 0;
        gbc.anchor = GridBagConstraints.CENTER;
        final JButton btnNewButton = new JButton("Add");
        btnNewButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for (File file : fileChooser.getSelectedFiles()) {
                    try {
                        model.addFileToModel(file);
                    } catch (IllegalArgumentException e1) {
                        showError(btnNewButton, file);
                    }
                }
            }
        });
        gbc.gridy = 1;
        root.add(btnNewButton, gbc);

        JButton btnNewButton_1 = new JButton("Remove");
        btnNewButton_1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (list.getSelectedIndices().length > 0) {
                    for (Object file : list.getSelectedValues()) {
                        model.removeFileFromModel((File) file);
                    }
                }
            }
        });
        gbc.gridx++;
        root.add(btnNewButton_1, gbc);

        final JButton btnNewButton_2 = new JButton("Check");
        btnNewButton_2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                File file = fileChooser.getSelectedFile();
                boolean found = false;
                for (File f : vector) {
                    if (file.getName().equals(f.getName())) {
                        found = true;
                        break;
                    }
                }
                if (found) {
                    showError(btnNewButton_2, file);
                } else {
                    JOptionPane.showMessageDialog(btnNewButton_2, "File " + file.getAbsolutePath() + " is not in the list yet");
                }
            }

        });
        gbc.gridx++;
        root.add(btnNewButton_2, gbc);
    }

    private void showError(Component parent, File file) {
        JOptionPane.showMessageDialog(parent, "File " + file.getName() + " already added");
    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                Test mainFrame = new Test();
                mainFrame.pack();
                mainFrame.setVisible(true);
            }
        });
    }
}
于 2012-05-09T21:36:20.297 回答
0
vector.contains(fileName)

先从那个开始?

于 2012-05-09T20:53:19.023 回答