JTree data from database
I'm working on the example at http://java.sun.com/docs/books/tutorial/uiswing/examples/components/Genealo开发者_高级运维gyExampleProject/src/components/GenealogyExample.java
I wanted to customize it in a way the data are pulled from a table instead (folder_id, folder_name, parent_id[foreign key to determine parent] .
Here is my code
public Person getGenealogyGraph() throws SQLException {
Connection con=null;
Statement st=null;
ResultSet rs=null;
String driver ="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/";
String db="java";
con=DriverManager.getConnection(url + db, "root", "");
ArrayList list=new ArrayList();
try {
String sql="Select * from folder";
st=con.createStatement();
rs=st.executeQuery(sql);
list.add("Current Folders");
while(rs.next()) {
String folderName = rs.getString("folder_name");
list.add(folderName);
// System.out.println(folderName);
//Person a1 = new Person(folderName);
}
} catch (Exception e) {
System.out.println(e);
}
rs.close();
st.close();
con.close();
Object hierarchy[]=list.toArray();
for(int i=1; i<hierarchy.length; i++) {
Person a+i=new Person(hierarchy[i]);
}
If I hardcode it as Person a1 = new Person("Jack (great-granddaddy)"); , it works fine. However, I wanted to put it in a loop, with the variable i :-
Object hierarchy[]=list.toArray();
for(int i=1; i<hierarchy.length; i++) {
Person a+i=new Person(hierarchy[i]);
}
How can I make the variable i and the "a" to be combined together? In PHP, we usually combine them with a "." , eg "a".$i;
Thanks :) Any other example on creating trees from database is greatly appreciated too. Thanks in advance
I'm not sure about what you're trying to do. But if you want to assign a dynamic name to your variables you should store your objects in a associative array (java.util.Map)
Map<String,Person> map= new HashMap<String,Person>();
(...)
map.put("a"+i,new Person(hierarchy[i]));
精彩评论