在开发系统的时候,尤其是前端需要展现一棵树的时候,经常需要构建一棵树来展现层级结构。
java中swing自带的tree就能满足这些需求,各种遍历方式都有。
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.Arrays;
import java.util.Enumeration;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
/**
* @ClassName: TreeExample
* @author kanpiaoxue
* @version 1.0
* @CreateTime: 2020/05/20 14:22:41
* @Description:
*/
public class TreeExample {
private static final DefaultMutableTreeNode root =
new DefaultMutableTreeNode(new BookInfo(1, "name-root"));
private static final DefaultMutableTreeNode note01 =
new DefaultMutableTreeNode(new BookInfo(2, "name-01"));
private static final DefaultMutableTreeNode note02 =
new DefaultMutableTreeNode(new BookInfo(3, "name-02"));
private static final DefaultMutableTreeNode note03 =
new DefaultMutableTreeNode(new BookInfo(4, "name-03"));
private static final DefaultMutableTreeNode note04 =
new DefaultMutableTreeNode(new BookInfo(5, "name-04"));
private static final DefaultMutableTreeNode note05 =
new DefaultMutableTreeNode(new BookInfo(6, "name-05"));
private static final DefaultMutableTreeNode note06 =
new DefaultMutableTreeNode(new BookInfo(7, "name-06"));
private static final DefaultMutableTreeNode note07 =
new DefaultMutableTreeNode(new BookInfo(8, "name-07"));
private static final DefaultMutableTreeNode note08 =
new DefaultMutableTreeNode(new BookInfo(9, "name-08"));
private static final DefaultMutableTreeNode note09 =
new DefaultMutableTreeNode(new BookInfo(10, "name-09"));
private static final DefaultMutableTreeNode note10 =
new DefaultMutableTreeNode(new BookInfo(11, "name-10"));
private static final Gson gson = new GsonBuilder()
.registerTypeAdapter(DefaultMutableTreeNode.class, new DefaultMutableTreeNodeSerializer())
.registerTypeAdapter(DefaultMutableTreeNode.class, new DefaultMutableTreeNodeDeserializer())
.setPrettyPrinting().create();
@SuppressWarnings("unchecked")
public static void main(String[] args) {
DefaultMutableTreeNode root = createNodes();
Enumeration rootEnumeration = root.breadthFirstEnumeration();
while (rootEnumeration.hasMoreElements()) {
DefaultMutableTreeNode n = rootEnumeration.nextElement();
System.out.println("-->" + n);
}
System.out.println("root:" + note10.getRoot());
TreeNode[] path = note10.getPath();
Arrays.stream(path).forEach(n -> {
System.out.println(n);
});
String json = gson.toJson(root);
System.out.println(json);
DefaultMutableTreeNode rootClone = gson.fromJson(json, DefaultMutableTreeNode.class);
System.out.println(rootClone.getDepth());
}
private static DefaultMutableTreeNode createNodes() {
/**
*
* 树的结构:
* https://www.draw.io/?lightbox=1&highlight=0000ff&edit=_blank&layers=1&nav=1&title=Untitled%20Diagram.drawio#R5ZlBb5swFMc%2FDcdK2CaEXJt1a6VNmsahZyu8AhPwkGNC0k8%2FJxgIc5exw2KnPQF%2FP4P94%2F31jPHYutx%2FEbzOvmEChUf9ZO%2BxTx6lNFoxdTgqh04hPgk6JRV5orVRiPNX6AO12uQJbCeBErGQeT0VN1hVsJETjQuB7TTsBYvpU2uegiHEG16Y6nOeyKxTI7oc9UfI06x%2FMglXXUvJ%2B2A9k23GE2zPJPbgsbVAlN1ZuV9DcaTXc%2Bn6ff5D6zAwAZWc0yF6%2Ff6SyOcYszL%2BsX6qavb4dKdfz44XjZ6wHqw89AQENlUCx5v4HrtHITNMseLFV8RaiUSJP0HKg353vJGopEyWhW7t7giJAXocuZa22IgNXBhunwFcpCAvxNGBr8pMwBKkOKh%2BAgou8910HFxnSDrEjRDVieb4D0wXf2d6hBHrywordbi%2FRcyBTczLD4M5tImZrD4MZxJZBW1wJgbokeoRUZvlEuKanybfqgL8FsEdCAn7ywzNKfcd%2BuKlyzf19XU71sIhJjurg4H%2FvyhFBqZTCXWNVGQb1O3bNpxpW6uuDQ3MzLlcZNR2MpqmDZ2jFAS2KZEZq3HHPRvMLbVWV%2BiBwTmwno5DWjljWkINTEvnMDngWnPhdmuupXNd67%2F9bq7jWjMdL21WXCcd74hzrn0H2w%2F%2B3Hy0ugFB3sEOxGzSdvcgfIP0wjnr269E9PYrEZn70UetliJifvatrCfkbyujRWg9H03b9p5xB1NofaeGmJ8jkXVKall7vXRSl%2BN%2FsFPb2e9E9vAL
*
*/
root.add(note01);
note01.add(note02);
note01.add(note03);
note01.add(note04);
note02.add(note05);
note05.add(note08);
note05.add(note09);
note09.add(note10);
note03.add(note06);
note04.add(note07);
return root;
}
}
输出内容:
写道
-->BookInfo [id=1, name=name-root]
-->BookInfo [id=2, name=name-01]
-->BookInfo [id=3, name=name-02]
-->BookInfo [id=4, name=name-03]
-->BookInfo [id=5, name=name-04]
-->BookInfo [id=6, name=name-05]
-->BookInfo [id=7, name=name-06]
-->BookInfo [id=8, name=name-07]
-->BookInfo [id=9, name=name-08]
-->BookInfo [id=10, name=name-09]
-->BookInfo [id=11, name=name-10]
root:BookInfo [id=1, name=name-root]
BookInfo [id=1, name=name-root]
BookInfo [id=2, name=name-01]
BookInfo [id=3, name=name-02]
BookInfo [id=6, name=name-05]
BookInfo [id=10, name=name-09]
BookInfo [id=11, name=name-10]
{
"allowsChildren": true,
"userObject": {
"id": 1,
"name": "name-root"
},
"children": [
{
"allowsChildren": true,
"userObject": {
"id": 2,
"name": "name-01"
},
"children": [
{
"allowsChildren": true,
"userObject": {
"id": 3,
"name": "name-02"
},
"children": [
{
"allowsChildren": true,
"userObject": {
"id": 6,
"name": "name-05"
},
"children": [
{
"allowsChildren": true,
"userObject": {
"id": 9,
"name": "name-08"
}
},
{
"allowsChildren": true,
"userObject": {
"id": 10,
"name": "name-09"
},
"children": [
{
"allowsChildren": true,
"userObject": {
"id": 11,
"name": "name-10"
}
}
]
}
]
}
]
},
{
"allowsChildren": true,
"userObject": {
"id": 4,
"name": "name-03"
},
"children": [
{
"allowsChildren": true,
"userObject": {
"id": 7,
"name": "name-06"
}
}
]
},
{
"allowsChildren": true,
"userObject": {
"id": 5,
"name": "name-04"
},
"children": [
{
"allowsChildren": true,
"userObject": {
"id": 8,
"name": "name-07"
}
}
]
}
]
}
]
}
5
参考资料:
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.util.Collections;
import javax.swing.tree.DefaultMutableTreeNode;
public class DefaultMutableTreeNodeSerializer implements JsonSerializer {
/* (non-Javadoc)
* @see com.google.gson.JsonSerializer#serialize(java.lang.Object, java.lang.reflect.Type, com.google.gson.JsonSerializationContext)
*/
@SuppressWarnings("unchecked")
@Override
public JsonElement serialize(DefaultMutableTreeNode src, java.lang.reflect.Type typeOfSrc,
JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("allowsChildren", src.getAllowsChildren());
jsonObject.add("userObject", context.serialize(src.getUserObject()));
if (src.getChildCount() > 0) {
jsonObject.add("children", context.serialize(Collections.list(src.children())));
}
return jsonObject;
}
}
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.util.List;
import javax.swing.tree.DefaultMutableTreeNode;
public class DefaultMutableTreeNodeDeserializer implements JsonDeserializer {
private static class POJO {
private boolean allowsChildren;
private Object userObject;
private List children;
// no need for: POJO parent
public DefaultMutableTreeNode toDefaultMutableTreeNode() {
DefaultMutableTreeNode node = new DefaultMutableTreeNode();
node.setAllowsChildren(allowsChildren);
node.setUserObject(userObject);
if (children != null) {
for (POJO child : children) {
node.add(child.toDefaultMutableTreeNode()); // recursion!
// this did also set the parent of the child-node
}
}
return node;
}
// Following setters needed by Gson's deserialization:
@SuppressWarnings("unused")
public void setAllowsChildren(boolean allowsChildren) {
this.allowsChildren = allowsChildren;
}
@SuppressWarnings("unused")
public void setUserObject(Object userObject) {
this.userObject = userObject;
}
@SuppressWarnings("unused")
public void setChildren(List children) {
this.children = children;
}
}
/* (non-Javadoc)
* @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, java.lang.reflect.Type, com.google.gson.JsonDeserializationContext)
*/
@Override
public DefaultMutableTreeNode deserialize(JsonElement json, java.lang.reflect.Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
return context.deserialize(json, POJO.class).toDefaultMutableTreeNode();
}
}
public class BookInfo {
private Integer id;
private String name;
/**
* @param id
* @param name
*/
public BookInfo(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
BookInfo other = (BookInfo) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
/**
* @return the id
*/
public Integer getId() {
return id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/*
* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
/**
* @param id
* the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "BookInfo [id=" + id + ", name=" + name + "]";
}
}