📜  Java Swing-JTree

📅  最后修改于: 2020-09-30 06:08:06             🧑  作者: Mango

Java JTree

JTree类用于显示树结构数据或层次结构数据。 JTree是一个复杂的组件。它的最顶部有一个“根节点”,它是树中所有节点的父节点。它继承了JComponent类。

JTree类声明

我们来看一下javax.swing.JTree类的声明。

public class JTree extends JComponent implements Scrollable, Accessible

常用的构造函数:

Constructor Description
JTree() Creates a JTree with a sample model.
JTree(Object[] value) Creates a JTree with every element of the specified array as the child of a new root node.
JTree(TreeNode root) Creates a JTree with the specified TreeNode as its root, which displays the root node.

Java JTree示例

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
style.add(color);
style.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
color.add(red); color.add(blue); color.add(black); color.add(green);
JTree jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args) {
new TreeExample();
}}

输出: