简体   繁体   中英

files duplication in java

I have added a few files into my JList via JFileChooser using a vector . I am trying to make it systematically by checking if the particular files are available in the JList or not. For example, if I add a file named 'abc.xml', I immediately check if that file exists in the JList or not.

Also I would like to check if the file is repeated only once. If it is repeated more than once ('abc.xml', 'abc.xml',...), there should be an error message indicating that the file is added more than once.

I am posting my complete code here;

         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);     
  }

What i get is, a msg box telling that the file is added already even when the file occurs only once.

What I expect is, when the file is added once, it should not display anything. But when it is added more than once, only then it should display a msg that the file is already added.

Can somebody help?

OK, Here is an example of something you describe. I am not quite sure what is the condition to refuse to add a File. This one is based on name, but I am wondering if you are not looking for a File.equals() using first getCanonicalFile() . I showed that in comment in the code too.

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);
    }
}

EDIT


Besides the fact that your code was incomplete, I managed to arrange it and make it work but it is really far from perfect. I also got rid of the MigLayout because it requires an additional library. Feel free to put it back.

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);
            }
        });
    }
}
vector.contains(fileName)

从第一个开始?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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