欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

树节点状态的保存和加载

程序员文章站 2022-06-08 09:20:36
...

保存树节点状态至数据库表中
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
String rows = "";
TreePath rootPath = new TreePath(((TreeNode) tree.getModel().getRoot()));
Enumeration enums = tree.getExpandedDescendants(rootPath);
while (enums != null && enums.hasMoreElements()) {
TreePath path = (TreePath) enums.nextElement();
int row = tree.getRowForPath(path);
rows += "," + row;
}
rows = (rows.startsWith(",") ? rows.substring(1) : rows);


TreePath path = tree.getSelectionPath();
int selectedRow = tree.getLeadSelectionRow();

String sql = "if ((select count(1) from CompanyStatus where loginUser='"+ loginUser +"')>0) "
+ "update CompanyStatus set expandedRow='" + rows + "', selectedRow=" + selectedRow + " where loginUser='"+ loginUser +"'"
+ " else insert into CompanyStatus (loginUser, expandedRow, selectedRow) values('"+ loginUser +"','" + rows + "'," + selectedRow + ")";
execute(sql);
}
});



从数据库中加载树的状态
public static void initCompanyStatus(JTree tree) {
int selectedRow = -1;
String[] expandedRow = {""};
String sql = "select expandedRow, selectedRow from CompanyStatus where loginUser='"+ loginUser +"'";
QueryDataSet dataset = executeQuery(sql);
if(dataset.getRowCount() > 0) {
expandedRow = dataset.getString("expandedRow").split(",");
selectedRow = dataset.getInt("selectedRow");
}

for(int i=0; i<tree.getRowCount(); i++) {
for(int j=0; j<expandedRow.length; j++) {
if(expandedRow[j].equals("" + i)) {
tree.expandRow(i);
break;
}
}
}

tree.setSelectionRow(selectedRow);
}
相关标签: SQL J#