gpt4 book ai didi

java - 检查JList中是否存在文件

转载 作者:行者123 更新时间:2023-12-02 07:51:01 25 4
gpt4 key购买 nike

我已从 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);

最佳答案

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

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

关于java - 检查JList中是否存在文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10226857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com