fill javaFX treeView from database dynamically - javafx

I have a table on database (code, composant, parent) where each node has a parent (a parent is also a component code), I need to fill a treeView dynamically from a select
#FXML
private TreeView tree;//declaration of the treeView
HashMap<Integer, composant> node = new HashMap<>(); //for child nodes
HashMap<Integer, composant> pere = new HashMap<>(); //for parent nodes
composant c; //object from component class
private void fillTree(String idSys) {
String query = "SELECT * FROM composant WHERE id=?";
try {
ps = cnx.prepareStatement(query);
ps.setString(1, idSys);
rs = ps.executeQuery();
while (rs.next()) {
int code = rs.getInt("code");
String composant = rs.getString("composant");
int parent = rs.getInt("parent");
String niveau = rs.getString("niveau");
int id = rs.getInt("id");
c = new composant(code, composant, niveau, parent, id);
node.put(code, c);
pere.put(parent, c);
}
ps.close();
rs.close();
} catch (Exception e) {
System.err.println("Error" + e);
}
TreeItem<String> system = new TreeItem<>(sys);
//brows and fill parents node
for (Integer k : pere.keySet()) {
composant p = pere.get(k);
TreeItem<String> parent = new TreeItem<>();
parent.setValue(p.getComposant());
//brows and fill child hashmap
for (Integer i : node.keySet()) {
composant c = node.get(i);
TreeItem<String> noeud = new TreeItem<>();
noeud.setValue(c.getComposant());
if (c.getParent() == k) {
//if the parent = 1 it must attach to the root node
if (k == 1) {
system.getChildren().add(noeud);
} else {
parent.getChildren().add(noeud);
}
}
}
}
tree.setRoot(system);
}
when compiling nothing appear on the window
this is what I've got

I'm almost sure the logic of creating the tree structure is wrong.
It's best if you simply create the TreeItems and store them by code in a map. Then iterate over the map and add every child to it's parent:
Map<Integer, TreeItem<String>> itemById = new HashMap<>();
Map<Integer, Integer> parents = new HashMap<>();
while (rs.next()) {
int code = rs.getInt("code");
String composant = rs.getString("composant");
int parent = rs.getInt("parent");
String niveau = rs.getString("niveau");
int id = rs.getInt("id");
itemById.put(code, new TreeItem<>(composant));
parents.put(code, parent);
}
ps.close();
rs.close();
TreeItem<String> root = null;
for (Map.Entry<Integer, TreeItem<String>> entry : itemById.entrySet()) {
Integer key = entry.getKey();
Integer parent = parents.get(key);
if (parent.equals(key)) {
// in case the root item points to itself, this is it
root = entry.getValue();
} else {
TreeItem<String> parentItem = itemById.get(parent);
if (parentItem == null) {
// in case the root item has no parent in the resultset, this is it
root = entry.getValue();
} else {
// add to parent treeitem
parentItem.getChildren().add(entry.getValue());
}
}
}
tree.setRoot(root);
Note that the above code assumes there is a unique root stored in the table. in case the query returns a forest where each root should be added to the root item of the TreeView, simply initialize root with a item instead
TreeItem<String> root = new TreeItem<>();
and add the items to root instead of setting the root
// root = entry.getValue();
root.getChildren().add(entry.getValue());

Related

TreeItem set multiple children under a parent/child

I am trying to get a list of equipment IDs to show under one data structure, instead of a listing with the equipment name alongside each ID.
I'm trying to get it to show:
Site Equipment
Inlet P1
M&C-SP2500
329
Sick Maihak-MCS 100e
330
336
538
Inlet P2
etc....
The data is from MySQL query and using an ObservableList.
private ObservableList<Customer_EquipTree> equiptrees;
TreeItem<String> rootItem = new TreeItem<String>("Site Equipment");
rootItem.setExpanded(true);
for (Customer_EquipTree equiptree : equiptrees) {
TreeItem<String> equip = new TreeItem<String>(equiptree.getEquipment());
TreeItem<String> clID = new TreeItem<String>(equiptree.getclID().toString());
boolean found = false;
for (TreeItem<String> siteDes : rootItem.getChildren()) {
if (siteDes.getValue().contentEquals(equiptree.getSiteDesignation())) {
siteDes.getChildren().add(equip);
equip.getChildren().add(clID);
found = true;
break;
}
}
if (!found) {
TreeItem<String> siteDes = new TreeItem<String>(equiptree.getSiteDesignation());
rootItem.getChildren().add(siteDes);
siteDes.getChildren().add(equip);
equip.getChildren().add(clID);
locationTreeView.setRoot(rootItem);
}
}
This is how I have
public class Customer_EquipTree {
private String SiteDesignation;
private String Equipment;
private Integer Checklistid;
private Integer clID;
public Customer_EquipTree(String SiteDesignation, String Equipment, Integer Checklistid, Integer clID) {
this.SiteDesignation = SiteDesignation;
this.Equipment = Equipment;
this.Checklistid = Checklistid;
this.clID = clID;
}
public String getSiteDesignation() {
return SiteDesignation;
}
public void setSiteDesignation(String SiteDesignation) {
this.SiteDesignation = SiteDesignation;
}
public String getEquipment() {
return Equipment;
}
public void setEquipment(String Equipment) {
this.Equipment = Equipment;
}
public Integer getChecklistid() {
return Checklistid;
}
public void setChecklistid(Integer Checklistid) {
this.Checklistid = Checklistid;
}
public Integer getclID() {
return clID;
}
public void setclID(Integer clID) {
this.clID = clID;
}
#Override
public String toString() {
return SiteDesignation + " " + Equipment.toString();
}
}
It seems to me that your Customer_EquipTree is basically a tuple of site, equipment and id and there is one for every id. It looks you need to look for existing equipment the same way you look for existing sites.
You should create a helper method for this to avoid code duplication:
public static <T> TreeItem<T> findOrInsert(TreeItem<T> parent, T childValue) {
for (TreeItem<T> child : parent.getChildren()) {
if (child.getValue().equals(childValue)) {
return child;
}
}
TreeItem<T> result = new TreeItem<T>(childValue);
parent.getChildren().add(result);
return result;
}
for (Customer_EquipTree equiptree : equiptrees) {
TreeItem<String> siteDes = findOrInsert(rootItem, equiptree.getSiteDesignation());
TreeItem<String> equip = findOrInsert(siteDes, equiptree.getEquipment());
equip.getChildren().add(new TreeItem<>(equiptree.getclID().toString()));
}
BTW: using ORDER BY in your sql query would allow you to simplify the tree creation a bit, since you can be sure the items with matching site/equipment values occur next to each other in the ResultSet, e.g.
TreeItem<String> rootItem = new TreeItem<String>("Site Equipment");
try (Statement st = conn.createStatement()) {
ResultSet rs = st.executeQuery("SELECT siteDesignation, equipment, clID FROM Customer_EquipTree ORDER BY siteDesignation, equipment");
String currentSite = null;
String currentEquipment = null;
TreeItem<Sting> tiSite = null;
TreeItem<String> tiEquipment = null;
while (rs.next()) {
String site = rs.getString(1);
String equipment = rs.getString(2);
String id = rs.getString(3);
if (!site.equals(currentSite)) {
currentSite = site;
tiSite = new TreeItem<>(site);
rootItem.getChildren().add(tiSite);
currentEquipment = null; // equipment needs to be replaced too
}
if (!equipment.equals(currentEquipment)) {
currentEquipment = equipment;
tiEquipment = new TreeItem<>(equipment);
tiSite.getChildren().add(tiEquipment);
}
tiEquipment.getChildren().add(new TreeItem<>(id));
}
}

Binding a TreeTableView

How can I bind TreeTableView? This gives me an error:
tblTreeView.rootProperty().bind(model.transactionProperty());
where transactionProperty():
public SimpleListProperty<Document> transactionsProperty() {
if(transactions == null){
transactions = new SimpleListProperty<>();
}
return transactions;
}
The rootProperty of a TreeTableView is an ObjectProperty<TreeItem<S>> (S The type of the TreeItem instances used in this TreeTableView)
TreeTableView<Document> treeTable = new TreeTableView<>();
ObjectProperty<TreeItem<Document>> rootProperty = treeTable.rootProperty();
it could be bound to an ObservableValue<TreeItem<S>>:
ObjectProperty<TreeItem<Document>> modelProperty = new SimpleObjectProperty<>();
rootProperty.bind(modelProperty);
modelProperty.set(myDocument); // will update the bound root property

using CSS to change node design

I dont know what I'am doing wrong with adding CSS style to node.
I have a main application window. Then I click menu item and another modal window opens as below(ModalWindow extends Stage):
FXMLLoader loader = new FXMLLoader(getClass().getResource(CONSTANTS.ROOT_USER_EDIT.string));
BorderPane editPane;
try {
editPane = new BorderPane(loader.load());
ModalWindow editWindow = new ModalWindow(Main.mainStage, editPane, "Edit user");
//its new stage with new scene, so we need to load this file again
editWindow.getScene().getStylesheets().add(getClass().getResource(CONSTANTS.CSS_PATH.string).toExternalForm());
UserData userData = (UserData)usersTable.getSelectionModel().getSelectedItem();
UserEditWindowController userEditWindowController = loader.getController();
userEditWindowController.fillWithData(userData);
editWindow.initModality(Modality.APPLICATION_MODAL);
editWindow.showAndWait();
} catch (IOException exception) {
ExceptionDialog exceptionDialog = new ExceptionDialog("Couldn't load UserEditWindow",exception);
exceptionDialog.showAndWait();
}
this CSS file is added:
#greenInfoTip {
-fx-graphic-text-gap: 20;
-fx-font-size: 44.0px ;
-fx-background: green;
-fx-background-color: rgb(128,255,128);
}
And I try to do this in root controller class:
infoTip.setId("greenInfoTip");
but with no effect. Is there something I'm doing wrong?
EDIT ItachiUchiha here is precisely what it looks like:
method is inside UserEditWindowController class:
#FXML
private void buttSaveAction(ActionEvent event){
//check if login and password doesn't contain spaces and is 4-16 characters long
String login = textFLogin.getText();
String password = textFPassword.getText();
boolean hasLoginWhiteSpace = isContainingWhiteSpace(login);
boolean hasPasswordWhiteSpace = isContainingWhiteSpace(password);
boolean isLoginMoreThan3 = (login.length() > 3)? true : false;
boolean isLoginLessThan17 = (login.length() < 17)? true : false;
boolean isPasswordMoreThan3 = (password.length() > 3)? true : false;
boolean isPasswordLessThan17 = (password.length() < 17)? true : false;
InfoTip infoTip = new InfoTip();
if( hasLoginWhiteSpace == false){
if( hasPasswordWhiteSpace == false ){
if( isLoginMoreThan3 == true && isLoginLessThan17 == true){
if( isPasswordMoreThan3 == true && isPasswordLessThan17 == true ){
//========login and password are correct
String query = "UPDATE users SET login = ?, password = ? WHERE employee_id = ?;";
try( Connection connection = Main.dataSource.getConnection() ){
try( PreparedStatement preparedStatement = connection.prepareStatement(query) ){
preparedStatement.setString(1, login);
preparedStatement.setString(2, password);
preparedStatement.setInt(3, currentUser.getiD());
preparedStatement.executeUpdate();
currentUser.setLogin(login);
currentUser.setPassword(password);
infoTip.getInfoTip().setId("greenInfoTip");
infoTip.showTip((Button)event.getSource(), "Saved");
}
}catch(Exception exception){
ExceptionDialog exceptionDialog = new ExceptionDialog("Error while loading data from database",exception);
exceptionDialog.showAndWait();
};
}else{ //password has less than 4 or more than 16 characters
infoTip.showTip(textFPassword, "no more than 16 and no less than 4 characters!");
}
}else{ //login has less than 4 or more than 16 characters
infoTip.showTip(textFLogin, "no more than 16 and no less than 4 characters!");
}
}else{ //password has white space
infoTip.showTip(textFPassword, "no spaces!");
}
}else{ //login has white space
infoTip.showTip(textFLogin, "no spaces!");
}
}
public class InfoTip {
private Tooltip infoTip;
public InfoTip(){
infoTip = new Tooltip();
}
private static Point2D getNodePos(Node node){ //getting node coordination on screen
Scene nodeScene = node.getScene();
final Point2D windowPos = new Point2D(nodeScene.getWindow().getX(), nodeScene.getWindow().getY());
final Point2D scenePos = new Point2D(nodeScene.getX(), nodeScene.getY());
final Point2D nodePos = node.localToScene(0.0, 0.0);
final Point2D nodePosOnScreen = new Point2D(windowPos.getX() + scenePos.getX() + nodePos.getX(),
windowPos.getY() + scenePos.getY() + nodePos.getY());
return nodePosOnScreen;
}
public void showTip(Node node, String text){
Point2D nodePosOnScreen = getNodePos(node);
infoTip = new Tooltip(text);
infoTip.setFont(new Font(15));
infoTip.setOpacity(0.9);
infoTip.setAutoFix(true);
infoTip.setAutoHide(true);
infoTip.show(node, nodePosOnScreen.getX()-30, nodePosOnScreen.getY() - 40);
}
public Tooltip getInfoTip(){
return infoTip;
}
}
The issue is with
infoTip = new Tooltip(text);
inside howTip(Node node, String text).
You are over-writing the old tooltip with id with a new object. Try using
infoTip.setText(text);

Add up childern values and write them in parent, JavaFX

I have creating this treetable
Now I want to sum up th children values and show the result in the parent cell under the related column. For example for Function 7 in column 2 and row 2 I want to right 2.0, and for Function 11 column 4 row 4 right 1.0 (function 12 + function 13)
Here is the code which produces the treetable.
root.setExpanded(true);
Set<String> combinedKeys = new HashSet<>(dc.getCombiFunc().keySet());
Set<String> funcAllKeys = new HashSet<>(dc.getSortedfuncAll().keySet());
funcAllKeys.removeAll(dc.getCombiFunc().keySet());
for (List<String> value : dc.getCombiFunc().values()) {
funcAllKeys.removeAll(value);
}
for (String valueremained : funcAllKeys) {
ArrayList<String> tempNameId = new ArrayList<>();
tempNameId.add(dc.getSortedfuncAll().get(valueremained));
// all elements which are not in combined functions (They are all
// orphan)
root.getChildren().add(new TreeItem<String>(tempNameId.get(0)));
}
// Getting Keys that have children//////
Set<String> keyFromcombined = new HashSet<>();
List<String> valueOfCombined = new ArrayList<String>();
for (Entry<String, List<String>> ent : dc.getCombiFunc().entrySet()) {
for (int i = 0; i < ent.getValue().size(); i++)
valueOfCombined.add(ent.getValue().get(i));
}
List<String> rootKeyList = new ArrayList<>();
for (String key : combinedKeys) {
if (!valueOfCombined.contains((key))) {
keyFromcombined.add(dc.getFuncAll().get(key));
rootKeyList.add(key);
}
}
String[] rootKeys = rootKeyList.toArray(new String[rootKeyList.size()]);
// ////////////////treetable////////////////////////////
treeTable.setRoot(root);
Arrays.stream(rootKeys).forEach(
rootKey -> root.getChildren().add(
createTreeItem(dc.getCombiFunc(), rootKey)));
// ////////////////First column/////////////////////////
TreeTableColumn<String, String> firstColumn = new TreeTableColumn<>("");
treeTable.getColumns().add(firstColumn);// Tree column
firstColumn.setPrefWidth(50);
firstColumn
.setCellValueFactory(new Callback<CellDataFeatures<String, String>, ObservableValue<String>>() {
public ObservableValue<String> call(
CellDataFeatures<String, String> p) {
return new ReadOnlyStringWrapper(p.getValue()
.getValue());
}
});
// //////////////////Rest Columns////////////////////////
for (Entry<String, String> ent : dc.getSortedAssignedOrg().entrySet()) {
TreeTableColumn<String, ArrayList<String>> col = new TreeTableColumn<>();
Label label = new Label(ent.getValue());
col.setGraphic(label);
label.setTooltip(new Tooltip(label.getText()));// tooltip for column
// headers
col.setPrefWidth(45);
// cell Value Factory////////////////////////
col.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<String, ArrayList<String>>, ObservableValue<ArrayList<String>>>() {
#Override
public ObservableValue<ArrayList<String>> call(
CellDataFeatures<String, ArrayList<String>> param) {
TreeMap<String, List<String>> temp = (TreeMap<String, List<String>>) dc
.getFuncTypeOrg().clone();
ArrayList<String> result = new ArrayList<>();
for (int i = 0; i < dc.getFuncTypeOrg().size(); i++) {
List<String> list = temp.firstEntry().getValue();
String key = temp.firstEntry().getKey();
if (list.get(1).equals(param.getValue().getValue())
&& !list.get(5).equals(label.getText())) {
result.add("white");
}
if (!root.isLeaf()) {
result.add("parent");
}
if (list.get(1).equals(param.getValue().getValue())
&& list.get(5).equals(label.getText())) {
result.add(0, list.get(2));// weight
if (list.size() > 6) {
result.add(1, list.get(list.size() - 1));// color
result.add(2, list.get(6));// App component
}
else
// result.add("white");
result.add("noOrg");
} else
temp.remove(key);
}
return new ReadOnlyObjectWrapper<ArrayList<String>>(result);
}
}); // end cell Value Factory
// //////////////cellfactory/////////////////////////
col.setCellFactory(new Callback<TreeTableColumn<String, ArrayList<String>>, TreeTableCell<String, ArrayList<String>>>() {
#Override
public TreeTableCell<String, ArrayList<String>> call(
TreeTableColumn<String, ArrayList<String>> param) {
return new TreeTableCell<String, ArrayList<String>>() {
public void updateItem(ArrayList<String> item,
boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setStyle("");
setText("");
} else if (item.contains("Green")) {
float weightInt = Float.parseFloat(item.get(0));
float res = weightInt * 1;
String resString = Float.toString(res);
this.setStyle("-fx-background-color:green");
setTooltip(new Tooltip(item.get(2)));
setText(resString);
} else if (item.contains("yellow")) {
this.setStyle("-fx-background-color:yellow");
setTooltip(new Tooltip(item.get(2)));
setText("0");
} else if (item.contains("white")) {
this.setStyle("-fx-background-color:linear-gradient(black, white); ");
// setText("DD");
} else if (item.contains("parent")) {
for (int i = 0; i < dc.getFuncTypeOrg().size(); i++) {
}
String text = param.getCellData(root).get(0);
// setText(text);
}
}
};
};
});// end cell factory
treeTable.getColumns().add(col);
}//end for loop col
TreeMap temp clones dc.getFuncTypeOrg(). In this TreeMap I have value for each child (color and the number). then in cellfactory i multiply value in color ( green = 1 and yellow = 0). Outside the loop I thought to make a treemap containg each parent as key and all it's children as value. Then I can sum up children values together and make a treemap in which first key is parent and as value the required value(or just string ArrayList ). After that I can check the name of cell in cellFactory and if it is a parent just right the value in the cell. I have been told how i can get treeitem values, and i am now here :
//after col loop ends
TreeMap<String, List<TreeItem<String>>> mytreemap = new TreeMap<>();
TreeMap<String, List<String>> parChild = new TreeMap<>();
for(TreeItem node: root.getChildren()){
if(!node.isLeaf())
mytreemap.put(node.getValue().toString(), node.getChildren());
}
for(Entry<String, List<TreeItem<String>>> ent: mytreemap.entrySet()){
for(TreeItem myItem : ent.getValue()){
// how can i fill parChild with parent as key and all its children as value?
System.out.println(ent.getKey()+" "+myItem.getValue());
}
}
treeTable.setPrefWidth(1200);
treeTable.setPrefHeight(500);
treeTable.setShowRoot(false);
treeTable.setTableMenuButtonVisible(true);
return treeTable; }
Here at setCellFactory
else if (item.contains("parent")) {
for (int i = 0; i < dc.getFuncTypeOrg().size(); i++) {
}
i can get the roots. Is there a way to do a recursion (up to the number of children and subchildren for that root cell) and add their value together and setText the parent cell to that value?
You can use onEditCommit method to add all childern values and show them in parent cell. For example
column1.setOnEditCommit((evt) -> {
//finalsing value of the cell
evt.getRowValue().getValue().setCellValue((evt.getNewValue()));
//Returns all the sibblings of the current cell
ObservableList<TreeItem> children = evt.getRowValue().getParent().getChildren();
int parentValue = 0;
for (TreeItem<> child : children) {
parentValue = parentValue + Integer.valueOf(child.getValue().getCellValue());
}
evt.getRowValue().getParent().getValue().setCellValue(parentValue);
});

NullPointer for list within map

This is a homework assignment, so explanations and pointers are preferred to solutions. Our previous assignment was to create a Graph template using an adjacency-matrix. This homework assignment was to modify the previous one using an adjacency-list instead. I have the previous matrix based code commented out for reference.
import java.util.*;
public class Graph {
public Node rootNode;
public List<Node> nodes = new ArrayList<Node>();
Map<Integer, List<Integer>> adjList;
//public int[][] adjMatrix;
int size;
public void setRootNode(Node n) {
rootNode = n;
}
public Node getRootNode() {
return rootNode;
}
public void addNode(Node n) {
nodes.add(n);
}
// This method will be called to make connect two nodes
public void connectNode(Node src, Node dst) {
// if (adjMatrix == null)
// {
// size = nodes.size();
// adjMatrix = new int[size][size];
// }
int srcIndex = nodes.indexOf(src);
int dstIndex = nodes.indexOf(dst);
// adjMatrix[srcIndex][dstIndex] = 1;
// adjMatrix[dstIndex][srcIndex] = 1;
if (!adjList.containsKey(srcIndex))
adjList.put(srcIndex, new ArrayList<Integer>());
adjList.get(srcIndex).add(dstIndex);
if (!adjList.containsKey(dstIndex))
adjList.put(dstIndex, new ArrayList<Integer>());
adjList.get(dstIndex).add(srcIndex);
}
private Node getUnvisitedChildNode(Node n) {
int index = nodes.indexOf(n);
for (int j = 0; j < size; j++)
//if (adjMatrix[index][j] == 1 && ((Node) nodes.get(j)).visited == false)
if (adjList.containsKey(index) && ((Node) nodes.get(j)).visited == false)
return nodes.get(j);
return null;
}
// BFS traversal: iterative version
public void bfs() {
// BFS uses a Queue data structure
Queue<Node> q = new LinkedList<Node>();
q.add(rootNode);
printNode(rootNode);
rootNode.visited = true;
while (!q.isEmpty()) {
Node n = q.remove();
Node child = null;
while ((child = getUnvisitedChildNode(n)) != null) {
child.visited = true;
printNode(child);
q.add(child);
}
}
}
// DFS traversal: iterative version
public void dfs() {
// DFS uses a Stack data structure
Stack<Node> s = new Stack<Node>();
s.push(rootNode);
rootNode.visited = true;
printNode(rootNode);
while (!s.isEmpty()) {
Node n = s.peek();
Node child = getUnvisitedChildNode(n);
if (child != null) {
child.visited = true;
printNode(child);
s.push(child);
} else
s.pop();
}
}
// Utility methods for clearing visited property of node
private void reset() {
for (Node n : nodes)
n.visited = false;
}
// Utility methods for printing the node's label
private void printNode(Node n) {
System.out.print(n.label + " ");
}
// get all neighboring nodes of node n.
public List<Node> getNeighbors(Node n) {
int srcIndex = nodes.indexOf(n);
List<Node> neighbors = new ArrayList<Node>();
// for (int j = 0; j < adjMatrix[srcIndex].length; j++)
// if (adjMatrix[srcIndex][j] == 1)
for (int j = 0; j < adjList.get(srcIndex).size(); j++)
if (adjList.get(srcIndex).contains(j))
neighbors.add(nodes.get(j));
return neighbors;
}
// implement recursive version of dfs
public void dfs(Node n) {
printNode(n); // visit the node
n.visited = true;
for (Node node : getNeighbors(n))
if (!node.visited)
dfs(node);
}
static class Node {
public char label;
public boolean visited = false;
public Node(char label) {
this.label = label;
}
}
public static void main(String[] args) {
// Lets create nodes as given as an example in the article
Node n0 = new Node('0');
Node n1 = new Node('1');
Node n2 = new Node('2');
Node n3 = new Node('3');
Node n4 = new Node('4');
Node n5 = new Node('5');
Node n6 = new Node('6');
Node n7 = new Node('7');
Node n8 = new Node('8');
// Create the graph, add nodes, create edges between nodes
Graph g = new Graph();
g.addNode(n0);
g.addNode(n1);
g.addNode(n2);
g.addNode(n3);
g.addNode(n4);
g.addNode(n5);
g.addNode(n6);
g.addNode(n7);
g.addNode(n8);
g.setRootNode(n8);
g.connectNode(n0, n1);
g.connectNode(n0, n3);
g.connectNode(n0, n8);
g.connectNode(n1, n7);
g.connectNode(n3, n2);
g.connectNode(n3, n4);
g.connectNode(n3, n4);
g.connectNode(n4, n8);
g.connectNode(n2, n7);
g.connectNode(n2, n5);
g.connectNode(n5, n6);
// Perform the DFS and BFS traversal of the graph
// System.out.print("DFS Traversal (Iterative): ");
// g.dfs();
// g.reset();
System.out.print("\nDFS Traversal (Recursive): ");
g.dfs(g.getRootNode());
g.reset();
System.out.print("\nBFS Traversal (Iterative): ");
g.bfs();
g.reset();
}
}
I'm getting a Null pointer in the connectNode method where I bring in the ArrayList. Again please keep in mind this is homework. Thank you in advance for all your help.
edit: How do you get line numbers to appear within stackoverflow?
if (!adjList.containsKey(srcIndex)) your adjList is null. You never set this List in your object.

Resources