I have a database with two columns named colNode,colLeaf
When I read data from the database and display it on the JTree
while (resultSet.next()) {
DefaultMutableTreeNode url = new DefaultMutableTreeNode(resultSet.getString("colNode"));
mutableTreeNode.add(url);
url.add(new DefaultMutableTreeNode(resultSet.getString("colLeaf")));
}
I would like if the value already exists on JTree colNode then colLeaf will be appended to the.I want to get the results in Figure 2 Please help me
Current output:
Desired output:
I assume you mean, that you want to group all the colLeaf
with the same colNode
?
I'd start by doing one of two things, either use the SQL to group and/or sort your results by colNode
, this way you could monitor the current "group" and when it changes, create a new TreeNode
Something like...
DefaultMutableTreeNode rootNode = ...;
DefaultMutableTreeNode groupNode = null;
String currentGroup = null;
while (resultSet.next()) {
String group = resultSet.getString("colNode");
if (currentGroup == null || !currentGroup.equals(group)) {
currentGroup = group;
group = new DefaultMutableTreeNode(group);
rootNode.add(groupNode);
}
group.add(new DefaultMutableTreeNode(resultSet.getString("colLeaf")));
}
for example.
Or, use somekind of Map
, to map all the colNode
values under the same key (colLeaf
)
Map<String, List<String>> mapGroups = new HashMap<>(25);
while (resultSet.next()) {
String group = resultSet.getString("colNode");
List<String> members = mapGroups.get(group);
if (members == null) {
members = new ArrayList<>(25);
mapGroups.put(group, members);
}
members.add(resultSet.getString("colLeaf"));
}
You would then use the mapGroups
to generate your TreeNode
s based on the key/value groups.
for example.
Personally, I think the first option is more efficient, but might require a more complex query, the second option is slower and requires more overhead, but models the data in manner which is similar to that which you are trying to achieve