我有两个数组,包括Filenames和JTextFields。如果文件存在,我想填充JTextField中的路径。有没有办法用for循环?我也尝试使用Hashmap,但这不起作用。
String[] Dateiliste = {
"A.txt",
"B.txt",
"C.txt",
"D.txt",
"E.txt",
"F.txt"
};
String[]textliste ={
"text1",
"text2",
"text3",
"text4",
"text5",
"text6",
};
Map<Integer, String> Dateilistestreda = new HashMap<Integer,String>();
Dateilistestreda.put(0,"text1");
Dateilistestreda.put(1,"text2");
Dateilistestreda.put(2,"text3");
Dateilistestreda.put(3,"text4");
Dateilistestreda.put(4,"text5");
Dateilistestreda.put(5,"text6");
for (int i = 0; i < Dateiliste.length; i++){
File f = new File (path + "\\" +Dateiliste[i]);
System.out.println(f);
if (f.exists() && !f.isDirectory()){
Dateilistestreda.get(i).setText(f.toString());
}
}
答案 0 :(得分:0)
由于您可以控制要选择的列表,为什么不创建一个包含两者的类,路径+ JTextField ......
例如:
import org.junit.Test;
import javax.swing.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class testclass {
@Test
public void test() {
String path = "C:/";
// Let's assume these are the real JTextFields you have:
final JTextField text1 = new JTextField();
final JTextField text2 = new JTextField();
final JTextField text3 = new JTextField();
final JTextField text4 = new JTextField();
final JTextField text5 = new JTextField();
final JTextField text6 = new JTextField();
// Here you just populates the List with the file names:
List<FilePath> files = new ArrayList<FilePath>() {{
add(new FilePath(text1, "A.txt"));
add(new FilePath(text2, "B.txt"));
add(new FilePath(text3, "C.txt"));
add(new FilePath(text4, "D.txt"));
add(new FilePath(text5, "E.txt"));
add(new FilePath(text6, "F.txt"));
}};
// And finally you just go one by one checking if it exists and updates the JTextField Text.
for (FilePath current : files) {
File file = new File(String.format("%s/%s", path, current.getName()));
if (file.exists() && !file.isDirectory()) {
current.getTextField().setText(current.getName());
}
System.out.println(current.getTextField().getText());
}
}
// This is just a simple class to hold both structures...
public class FilePath {
private JTextField textField;
private String name;
public FilePath(JTextField textField, String path) {
this.textField = textField;
this.name = path;
}
public JTextField getTextField() {
return textField;
}
public String getName() {
return name;
}
}
}
希望它有所帮助...