检查JList中是否存在文件

时间:2012-04-19 11:15:09

标签: java file jlist

我在JFileChooser的JList中添加了一些文件。我正在添加一个名为“CHECK”的新按钮,当单击该按钮时,它会告诉JList中是否存在特定文件(已添加的文件中)。如果你们中的任何一个人能告诉我这一步的正确程序是真的很棒。

提前感谢你..

这是我目前的代码;

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

    JScrollPane scrollPane = new JScrollPane();
    getContentPane().add(scrollPane, "cell 10 1 3 8,grow");

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

    JPanel panel = new JPanel();
    getContentPane().add(panel, "cell 3 4 7 1,grow");

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

            }
    });
    panel.add(btnNewButton);

    JButton btnNewButton_1 = new JButton("Remove Files");
    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();

        }   
        });
    panel.add(btnNewButton_1);

    JButton btnNewButton_2 = new JButton("Check For Files");
    btnNewButton_2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String name = "";
            if(list.getSelectedIndices().length > 0 ) {
                       //// to check if a file exists /////
            }
            }
             });

    panel.add(btnNewButton_2);

2 个答案:

答案 0 :(得分:1)

Vector有一个contains方法,您可以使用:

if(vector.contains(file)){
   //Vector has the file
}

答案 1 :(得分:1)

  1. 请将集合框架的List用于var类型,将ArrayList用于具体类来实例化。自Java 1.2以来,Vector已经成为过去。
  2. 迭代所选文件,检查两端的规范路径:
  3. final File toCheck = fileToCheckInList.getCanonicalFile();
    for (File file : fileChooser.getSelectedFiles())
      if (file.getCanonicalFile().equals(toCheck)) return true;