[英]Can i use a string variable as a datatype to create other variables in java
[英]Can i use a String as variable in java
我有兩個數組,分別是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());
}
}
由於您可以控制要選擇的列表,因此為什么不創建一個同時包含路徑和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;
}
}
}
希望能幫助到你...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.