import javax.swing.*
class TreeDemo extends JFrame
{
public TreeDemo()
{
setSize(400,300)
setTitle("演示怎样使用JTree")
show()
JScrollPane jPanel=new JScrollPane()
getContentPane().add(jPanel)
JTree jtree=new JTree()
jPanel.getViewport().add(jtree,null)
validate()
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
}
}
public class Example5_25
{
public static void main(String[] args)
{
TreeDemo frame=new TreeDemo()
}
}
其中JScrollPane是一个带滚动条的面板类。
将对象加入到带滚动条的面板类中,在将已建的数放入到其中。
就可建立一个系统默认的树结构。
import java.util.Stack//导入栈包public class newtree {
private newtree lchild// 声明数据成员
private newtree rchild
private char data
private newtree root
public newtree(newtree l, newtree r, char data) {// 有参构造函数进行成员赋值
lchild = l
rchild = r
this.data = data
}
public newtree() {// 无参构造函数创建树
newtree f = new newtree(null, null, 'f')
newtree g = new newtree(null, null, 'g')
newtree d = new newtree(null, null, 'd')
newtree e = new newtree(null, null, 'e')
newtree b = new newtree(d, e, 'b')
newtree c = new newtree(f, g, 'c')
newtree a = new newtree(b, c, 'a')
this.root=a
}
public void visit(newtree p) {/* 输出数据 */
System.out.print(p.data)// 访问结点
}
@SuppressWarnings("unchecked")
public void InOrder() {/* 输入数据 */
newtree p=this.root//你建了一棵树要把根节点赋值进去啊
Stack s = new Stack()
while (p != null || !s.isEmpty()) /* 处理数据:进行中序遍历 */
{
if (p != null) {
s.push(p)
p = p.lchild
} else {
p = (newtree) s.pop()
p.visit(p)//this指的是当前的类对象
p = p.rchild
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
newtree h = new newtree()// 声明变量,变量赋值
h.InOrder()
}
}
//根据你的代码改了一个
import java.util.Stack//导入栈包
public class newtree {
public Tree createTree() {// 无参构造函数创建树
Tree f = new Tree(null, null, 'f')
Tree g = new Tree(null, null, 'g')
Tree d = new Tree(null, null, 'd')
Tree e = new Tree(null, null, 'e')
Tree b = new Tree(d, e, 'b')
Tree c = new Tree(f, g, 'c')
Tree a = new Tree(b, c, 'a')
return a
}
public void InOrder(Tree p) {/* 输入数据 */
Stack<Tree> s = new Stack<Tree>()
while (p != null || !s.isEmpty()) { /* 处理数据:进行中序遍历 */
if (p != null) {
s.push(p)
p = p.lchild
} else {
p = s.pop()
System.out.print(p.data)
p = p.rchild
}
}
}
public void inOrder1(Tree p) {
if (p == null)
return
inOrder1(p.lchild)
System.out.print(p.data)
inOrder1(p.rchild)
}
public static void main(String[] args) {
newtree h = new newtree()// 声明变量,变量赋值
h.InOrder(h.createTree())
System.out.println()
h.inOrder1(h.createTree())
}
}
class Tree {
Tree lchild// 声明数据成员
Tree rchild
char data
Tree(Tree lchild, Tree rchild, char data) {
this.lchild = lchild
this.rchild = rchild
this.data = data
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)