透過連線資料庫來動態的生成樹的問題

alun發表於2003-06-24
看看這段程式碼,我想要實現的是透過連線資料庫來動態的生成樹,
問題是在“////////”處
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class TreeView1 extends JApplet {
JTextArea textArea = new JTextArea();
String sDBDriver="com.microsoft.jdbc.sqlserver.SQLServerDriver";
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=login";
String user="sa";
String password="";
ResultSet rs;
ResultSet rs2;

public void init() {
Class.forName(sDBDriver); //連線資料庫並讀出相關欄位
Connection conn= DriverManager.getConnection(url,user,password);
Statement
stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from modules where m_parentId=0";
rs=stmt.executeQuery(sql);
while(rs.next()) {
int id=rs.getInt(1);
String iid=rs.getString(3);
stmt=conn.createStatement();
DefaultMutableTreeNode root = new DefaultMutableTreeNode(iid);
rs2 = stmt.executeQuery("select * from modules where m_parentId='"+id+"'");
while (rs2.next()) {
String iid1=rs2.getString(3);
stmt=conn.createStatement();
DefaultMutableTreeNode ParenId1 = new DefaultMutableTreeNode(iid1);
root.add(ParenId1);
}
JTree tree=new JTree(root); //生成樹
JScrollPane scrollpane=new JScrollPane(tree);
Container con=getContentPane();
con.add(scrollpane);}
/*rs.close();
stmt.close();
conn.close();*/

JSplitPane splitPane = new JSplitPane(
JSplitPane.HORIZONTAL_SPLIT,
new JScrollPane(tree), ////////錯誤是找不到我這個包裡面的tree
splitPane.setDividerLocation(150);
textArea.setFont(new Font("Serif", Font.PLAIN, 17));

getContentPane().add(splitPane, BorderLayout.CENTER);

tree.addTreeSelectionListener( ////////這裡的提示同上
new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
TreePath path = e.getNewLeadSelectionPath();
String s = new String();

if(path != null) {
s += "New lead selection path: " +
path.toString() + "\n";
}
else
s += "selection cleared\n";

path = e.getOldLeadSelectionPath();

if(path != null) {
s += "Old lead selection path: " +
path.toString() + "\n";
}
else
s += "No previous lead selection\n";

textArea.append(s + "\n");
printSelectionInformation(e);
}
void printSelectionInformation(TreeSelectionEvent e) {
showPaths(e);

textArea.append("\n----------------------------");
textArea.append("----------------------------\n");
}
private void showPaths(TreeSelectionEvent e) {
TreePath[] paths = e.getPaths();

textArea.append("Number of Paths: " +
paths.length + "\n");

for(int i=0; i < paths.length; ++i) {
TreePath path = paths;
boolean wasAdded = e.isAddedPath(path);

textArea.append(" path " + i + ": ");
textArea.append(path +
(wasAdded ? " added to selection" :
" removed from selection") + "\n");
}
}
});
}
}

請各位看看,如果有程式碼帖上來看看也可以,謝謝!

相關文章