import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
// Knotenklasse zum Speichern für Kundenname & KundenID
class CTreeNode extends DefaultMutableTreeNode{
int id;
// 1.Konstruktor
CTreeNode(Object title){
super(title);
}
// 2.Konstruktor
CTreeNode(int id, Object title){
super(title);
this.id = id;
}
public void setID(int id){this.id = id;}
public int getID(){return this.id;}
}
// DefaultTreeModel zum erstellen von Kunden & Produkten
class CTreeModel extends DefaultTreeModel{
private Connection con;
// Konstruktor:
CTreeModel(CTreeNode root, Connection con){
super(root);
this.con = con;
}
// Methode, um Baumelemente einzufügen:
private void insertNode(CTreeNode newNode, CTreeNode parent){
int i = getChildCount(parent);
insertNodeInto(newNode, parent, i);
}
//Methode, mit der Du die Kunden an die Wurzel hängst
public void createCustomers() throws SQLException{
if (con == null)return;
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("Select KundenID, Kundenname from Kunde");
while (rs != null && rs.next()) {
insertNode(new CTreeNode(rs.getInt(1), rs.getString(2)), (CTreeNode)this.getRoot());
}
}
// dann: Methode, um die Produkte an die Kunden zu hängen
// (man könnte Kunden & Produkte natürlich auch zusammen in 1 Methode
// einlesen)
public void createProducts() throws SQLException {
if (con == null)return;
Statement stmt = con.createStatement();
// Kundenknoten durchlaufen und deren KundenID holen
// -> sollte hier mit Produkt-Tabelle verknüpft sein
for (int c = 0; c <((CTreeNode)this.getRoot()).getChildCount(); c++){
CTreeNode customer = (CTreeNode)((CTreeNode)this.getRoot()).getChildAt(c);
ResultSet rs = stmt.executeQuery("Select ProduktID, Produktname from Produkte p " +
"where p.KundenID = " + customer.getID());
while (rs != null && rs.next()) {
CTreeNode product = new CTreeNode(rs.getInt(1), rs.getString(2));
insertNode(product, customer);
}
}
}
}