十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
JTree组件被用来以树的形式显示数据,一层套一层,看起来清晰明了,使用户很方便地就了解到各个节点之间的层次关系,可以很容易地找到相关的数据。
创新互联专注于耒阳企业网站建设,响应式网站,商城系统网站开发。耒阳网站建设公司,为耒阳等地区提供建站服务。全流程按需制作网站,专业设计,全程项目跟踪,创新互联专业和态度为您提供的服务
例如 Windows 系统的文件管理器,它就是一个典型的树层次结构。
JTree的构造函数:
·JTree() 建立一棵默认的树。
·JTree(Hashtable data) 利用Hashtable建立树。
·JTree(Object[] data) 利用数组建立树。
·JTree(TreeModel model) 利用TreeModel建立树。
·JTree(TreeNode root) 建立以root为根的树。
·JTree(TreeNode root,Boolean children) 建立以 root 为根的树,并设定是否允许有子节点。
·JTree(Vector value) 利用Vector建立树。
使用一个JTree可以简单地像下面这样表示:
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeDemo {
public static void main(String[] args) {
// 创建没有父节点和子节点、但允许有子节点的树节点,并使用指定的用户对象对它进行初始化。
// public DefaultMutableTreeNode(Object userObject)
DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("软件部");
node1.add(new DefaultMutableTreeNode(new User("小花")));
node1.add(new DefaultMutableTreeNode(new User("小虎")));
node1.add(new DefaultMutableTreeNode(new User("小龙")));
DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("销售部");
node2.add(new DefaultMutableTreeNode(new User("小叶")));
node2.add(new DefaultMutableTreeNode(new User("小雯")));
node2.add(new DefaultMutableTreeNode(new User("小夏")));
DefaultMutableTreeNode top = new DefaultMutableTreeNode("职员管理");
top.add(new DefaultMutableTreeNode(new User("总经理")));
top.add(node1);
top.add(node2);
final JTree tree = new JTree(top);
JFrame f = new JFrame("JTreeDemo");
f.add(tree);
f.setSize(300, 300);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 添加选择事件
tree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree
.getLastSelectedPathComponent();
if (node == null)
return;
Object object = node.getUserObject();
if (node.isLeaf()) {
User user = (User) object;
System.out.println("你选择了:" + user.toString());
}
}
});
}
}
class User {
private String name;
public User(String n) {
name = n;
}
// 重点在toString,节点的显示文本就是toString
public String toString() {
return name;
}
}
这是代码,你可以自己调试一下。
数据结构如下:
CREATE TABLE dtree (
id int,
pid int,
name varchar(200),
url varchar(200),
title varchar(200),
target varchar(200),
icon varchar(200),
iconopen varchar(200),
opened bit);
为了实现获取数据库变量功能,需要建立一个DTree类,并编译生成CLASS文件,放入\WEB-INF\classes文件夹下。
DTree类代码如下:
package work3;
public class DTree {
private int id;
private int pid;
private String name;
private String url;
private String title;
private String target;
private String icon;
private String iconOpen;
private int opened;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getIconOpen() {
return iconOpen;
}
public void setIconOpen(String iconOpen) {
this.iconOpen = iconOpen;
}
public int getOpened() {
return opened;
}
public void setOpened(int opened) {
this.opened = opened;
}
}
work3.jsp代码如下:
%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%
%@ page import="java.sql.*"%
jsp:useBean id='settree' scope="application" class="work3.DTree" /
!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
""
html
head
meta http-equiv="Content-Type" content="text/html; charset=GB18030"
link rel="StyleSheet" href="dtree.css" type="text/css" /
script type="text/javascript" src="dtree.js"/script
titledTree in MySQL/title
/head
body
h2
Example
/h2
div class="dtree"
p
a href="javascript: d.openAll();"open all/a |
a href="javascript: d.closeAll();"close all/a
/p
script type="text/javascript"
!--
d = new dTree('d');
%
//驱动程序名
String driverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
//数据库用户名
String userName = "sa";
//密码
String userPwd = "1";
//数据库名
String dbName = "master";
//表名
String tableName = "dtree";
//连接字符串
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName="+dbName;
//加载驱动
Class.forName(driverName).newInstance();
//连接数据库
java.sql.Connection conn = DriverManager.getConnection(url,userName,userPwd);
//得到Statement实例
java.sql.Statement statement = conn.createStatement();
//查询数据
String sql = "select * from " + tableName;
//返回结果
java.sql.ResultSet rs = statement.executeQuery(sql);
//获取变量
while (rs.next()) {
settree.setId(rs.getInt(1));
settree.setPid(rs.getInt(2));
settree.setName(rs.getString(3));
settree.setUrl(rs.getString(4));
settree.setTitle(rs.getString(5));
settree.setTarget(rs.getString(6));
settree.setIcon(rs.getString(7));
settree.setIconOpen(rs.getString(8));
settree.setOpened(rs.getInt(9));
if(settree.getPid()==0)
settree.setOpened(1);
%
d.add(%=settree.getId()%,%=settree.getPid()%,'%=settree.getName()%','%=settree.getUrl()%','%=settree.getTitle()%','%=settree.getTarget()%','','',%=settree.getOpened()%);
%
}
%
document.write(d);
//--
/script
/div
/body
/html
按照你的要求加详细注释的圣诞树Java程序如下:(编程思想在注释中说明)
public class ShengDanShu2 {
//这个程序的编程思想是利用对for循环变量i的控制达到一层循环代替双层循环的目的
public static void main(String[] args) {
int n=5; //初始化打印圣诞树层数变量n
int a=0; //初始化打印前置空格数变量a
int b=0; //初始化打印星号数变量b
for(int i=1;i =n;i++){ //打印n层圣诞树
if(a!=(n-i)){ //如果前置空格数不等于n-i
System.out.print(" "); //打印一个空格
a++; //前置空格数加一
i=i-1; //i变量减一 目的是固定住i变量不变直到a==n-i
}else if(b!=(2*i-1)){ //如果星号数不等于2*i-1
System.out.print("*"); //打印一个星号
b++; //星号数加一
i=i-1; //i变量减一 目的是固定住i变量不变直到b==2*i-1
}else if(a==(n-i) b==(2*i-1)){//当以上两个条件都满足时,换行初始化a和b为0
System.out.println(); //打印换行
a=0; //对新的一行重新初始化前置空格数变量a
b=0; //对新的一行重新初始化打印星号数变量b
//这里没有控制for循环的i变量减一,因为这时i变量加一,开始新一行。
}
}
}
}
运行结果:
*
***
*****
*******
*********
二叉树的相关操作,包括创建,中序、先序、后序(递归和非递归),其中重点的是java在先序创建二叉树和后序非递归遍历的的实现。
package com.algorithm.tree;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
import java.util.concurrent.LinkedBlockingQueue;
public class Tree {
private Node root;
public Tree() {
}
public Tree(Node root) {
this.root = root;
}
//创建二叉树
public void buildTree() {
Scanner scn = null;
try {
scn = new Scanner(new File("input.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
root = createTree(root,scn);
}
//先序遍历创建二叉树
private Node createTree(Node node,Scanner scn) {
String temp = scn.next();
if (temp.trim().equals("#")) {
return null;
} else {
node = new Node((T)temp);
node.setLeft(createTree(node.getLeft(), scn));
node.setRight(createTree(node.getRight(), scn));
return node;
}
}
//中序遍历(递归)
public void inOrderTraverse() {
inOrderTraverse(root);
}
public void inOrderTraverse(Node node) {
if (node != null) {
inOrderTraverse(node.getLeft());
System.out.println(node.getValue());
inOrderTraverse(node.getRight());
}
}
//中序遍历(非递归)
public void nrInOrderTraverse() {
StackNode stack = new StackNode();
Node node = root;
while (node != null || !stack.isEmpty()) {
while (node != null) {
stack.push(node);
node = node.getLeft();
}
node = stack.pop();
System.out.println(node.getValue());
node = node.getRight();
}
}
//先序遍历(递归)
public void preOrderTraverse() {
preOrderTraverse(root);
}
public void preOrderTraverse(Node node) {
if (node != null) {
System.out.println(node.getValue());
preOrderTraverse(node.getLeft());
preOrderTraverse(node.getRight());
}
}
//先序遍历(非递归)
public void nrPreOrderTraverse() {
StackNode stack = new StackNode();
Node node = root;
while (node != null || !stack.isEmpty()) {
while (node != null) {
System.out.println(node.getValue());
stack.push(node);
node = node.getLeft();
}
node = stack.pop();
node = node.getRight();
}
}
//后序遍历(递归)
public void postOrderTraverse() {
postOrderTraverse(root);
}
public void postOrderTraverse(Node node) {
if (node != null) {
postOrderTraverse(node.getLeft());
postOrderTraverse(node.getRight());
System.out.println(node.getValue());
}
}
//后续遍历(非递归)
public void nrPostOrderTraverse() {
StackNode stack = new StackNode();
Node node = root;
Node preNode = null;//表示最近一次访问的节点
while (node != null || !stack.isEmpty()) {
while (node != null) {
stack.push(node);
node = node.getLeft();
}
node = stack.peek();
if (node.getRight() == null || node.getRight() == preNode) {
System.out.println(node.getValue());
node = stack.pop();
preNode = node;
node = null;
} else {
node = node.getRight();
}
}
}
//按层次遍历
public void levelTraverse() {
levelTraverse(root);
}
public void levelTraverse(Node node) {
QueueNode queue = new LinkedBlockingQueueNode();
queue.add(node);
while (!queue.isEmpty()) {
Node temp = queue.poll();
if (temp != null) {
System.out.println(temp.getValue());
queue.add(temp.getLeft());
queue.add(temp.getRight());
}
}
}
}
//树的节点
class Node {
private Node left;
private Node right;
private T value;
public Node() {
}
public Node(Node left,Node right,T value) {
this.left = left;
this.right = right;
this.value = value;
}
public Node(T value) {
this(null,null,value);
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
测试代码:
package com.algorithm.tree;
public class TreeTest {
/**
* @param args
*/
public static void main(String[] args) {
Tree tree = new Tree();
tree.buildTree();
System.out.println("中序遍历");
tree.inOrderTraverse();
tree.nrInOrderTraverse();
System.out.println("后续遍历");
//tree.nrPostOrderTraverse();
tree.postOrderTraverse();
tree.nrPostOrderTraverse();
System.out.println("先序遍历");
tree.preOrderTraverse();
tree.nrPreOrderTraverse();
//
}
}
java构造二叉树,可以通过链表来构造,如下代码:
public class BinTree {
public final static int MAX=40;
BinTree []elements = new BinTree[MAX];//层次遍历时保存各个节点
int front;//层次遍历时队首
int rear;//层次遍历时队尾
private Object data; //数据元数
private BinTree left,right; //指向左,右孩子结点的链
public BinTree()
{
}
public BinTree(Object data)
{ //构造有值结点
this.data = data;
left = right = null;
}
public BinTree(Object data,BinTree left,BinTree right)
{ //构造有值结点
this.data = data;
this.left = left;
this.right = right;
}
public String toString()
{
return data.toString();
}
//前序遍历二叉树
public static void preOrder(BinTree parent){
if(parent == null)
return;
System.out.print(parent.data+" ");
preOrder(parent.left);
preOrder(parent.right);
}
//中序遍历二叉树
public void inOrder(BinTree parent){
if(parent == null)
return;
inOrder(parent.left);
System.out.print(parent.data+" ");
inOrder(parent.right);
}
//后序遍历二叉树
public void postOrder(BinTree parent){
if(parent == null)
return;
postOrder(parent.left);
postOrder(parent.right);
System.out.print(parent.data+" ");
}
// 层次遍历二叉树
public void LayerOrder(BinTree parent)
{
elements[0]=parent;
front=0;rear=1;
while(frontrear)
{
try
{
if(elements[front].data!=null)
{
System.out.print(elements[front].data + " ");
if(elements[front].left!=null)
elements[rear++]=elements[front].left;
if(elements[front].right!=null)
elements[rear++]=elements[front].right;
front++;
}
}catch(Exception e){break;}
}
}
//返回树的叶节点个数
public int leaves()
{
if(this == null)
return 0;
if(left == nullright == null)
return 1;
return (left == null ? 0 : left.leaves())+(right == null ? 0 : right.leaves());
}
//结果返回树的高度
public int height()
{
int heightOfTree;
if(this == null)
return -1;
int leftHeight = (left == null ? 0 : left.height());
int rightHeight = (right == null ? 0 : right.height());
heightOfTree = leftHeightrightHeight?rightHeight:leftHeight;
return 1 + heightOfTree;
}
//如果对象不在树中,结果返回-1;否则结果返回该对象在树中所处的层次,规定根节点为第一层
public int level(Object object)
{
int levelInTree;
if(this == null)
return -1;
if(object == data)
return 1;//规定根节点为第一层
int leftLevel = (left == null?-1:left.level(object));
int rightLevel = (right == null?-1:right.level(object));
if(leftLevel0rightLevel0)
return -1;
levelInTree = leftLevelrightLevel?rightLevel:leftLevel;
return 1+levelInTree;
}
//将树中的每个节点的孩子对换位置
public void reflect()
{
if(this == null)
return;
if(left != null)
left.reflect();
if(right != null)
right.reflect();
BinTree temp = left;
left = right;
right = temp;
}
// 将树中的所有节点移走,并输出移走的节点
public void defoliate()
{
if(this == null)
return;
//若本节点是叶节点,则将其移走
if(left==nullright == null)
{
System.out.print(this + " ");
data = null;
return;
}
//移走左子树若其存在
if(left!=null){
left.defoliate();
left = null;
}
//移走本节点,放在中间表示中跟移走...
String innerNode += this + " ";
data = null;
//移走右子树若其存在
if(right!=null){
right.defoliate();
right = null;
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BinTree e = new BinTree("E");
BinTree g = new BinTree("G");
BinTree h = new BinTree("H");
BinTree i = new BinTree("I");
BinTree d = new BinTree("D",null,g);
BinTree f = new BinTree("F",h,i);
BinTree b = new BinTree("B",d,e);
BinTree c = new BinTree("C",f,null);
BinTree tree = new BinTree("A",b,c);
System.out.println("前序遍历二叉树结果: ");
tree.preOrder(tree);
System.out.println();
System.out.println("中序遍历二叉树结果: ");
tree.inOrder(tree);
System.out.println();
System.out.println("后序遍历二叉树结果: ");
tree.postOrder(tree);
System.out.println();
System.out.println("层次遍历二叉树结果: ");
tree.LayerOrder(tree);
System.out.println();
System.out.println("F所在的层次: "+tree.level("F"));
System.out.println("这棵二叉树的高度: "+tree.height());
System.out.println("--------------------------------------");
tree.reflect();
System.out.println("交换每个节点的孩子节点后......");
System.out.println("前序遍历二叉树结果: ");
tree.preOrder(tree);
System.out.println();
System.out.println("中序遍历二叉树结果: ");
tree.inOrder(tree);
System.out.println();
System.out.println("后序遍历二叉树结果: ");
tree.postOrder(tree);
System.out.println();
System.out.println("层次遍历二叉树结果: ");
tree.LayerOrder(tree);
System.out.println();
System.out.println("F所在的层次: "+tree.level("F"));
System.out.println("这棵二叉树的高度: "+tree.height());
}