How To Set JTable Values Into JTree Nodes Using Java NetBeans
In this Java Tutorial we will see How To Get JTable Rows Data And Set It Into JTree Node Using For Loop + DefaultMutableTreeNode + DefaultTreeModel On Button Click Event In Java NetBeans .
Project Source Code:
private void jButtonToJTreeActionPerformed(java.awt.event.ActionEvent evt) {
// create jtree root
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Table Data");
// rows
for(int i = 0; i < jTable1.getRowCount(); i++){
int rowIndex = i+1;
DefaultMutableTreeNode row = new DefaultMutableTreeNode("Row "+ rowIndex);
// columns
for(int c = 0; c < jTable1.getColumnCount(); c++)
{
DefaultMutableTreeNode node = new DefaultMutableTreeNode(jTable1.getValueAt(i, c));
// add data to the row
row.add(node);
}
// add the row to the root
root.add(row);
}
DefaultTreeModel model = new DefaultTreeModel(root);
jTree1.setModel(model);
}