创建树组件,有两种方式
- 静态创建树形组件
- 动态创建树形组件
树组件,和表格组件、文本区组件是一样的,都没有滚动条,需要放到JScrollPane中展示全部数据
你只需要查看一下其源代码就知道怎么回事了
静态创建树组件代码
package Tree.mugejiangtang;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
/**
*
* 根节点、叶子节点
* 把叶子节点归类
* 把根节点放到JTree构造函数的参数中
*
*/
public class NewFrame10 extends JFrame {
JTree familyTree;
JScrollPane jspFamily;
public NewFrame10(){
init();
}
private void init( ){
Container container = this.getContentPane();//获得窗体的主体区域
container.setLayout(null);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("曹操");
DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("曹昂");
DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("曹丕");
DefaultMutableTreeNode a3 = new DefaultMutableTreeNode("曹植");
DefaultMutableTreeNode a4 = new DefaultMutableTreeNode("曹彰");
root.add(a1);
root.add(a2);
root.add(a3);
root.add(a4);
DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("曹睿");
DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("曹霖");
DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("曹志");
a2.add(b1);
a2.add(b2);
a3.add(b3);
DefaultMutableTreeNode c1 = new DefaultMutableTreeNode("曹芳");
b1.add(c1);
familyTree = new JTree(root);
familyTree.setFont(new Font("微软雅黑", Font.PLAIN, 18));
jspFamily = new JScrollPane(familyTree);
jspFamily.setSize(300, 250);
jspFamily.setLocation(30, 30);
container.add(jspFamily);
}
}
测试代码
package Tree.mugejiangtang;
import javax.swing.JFrame;
public class Test {
public static void main(String[] args) {
NewFrame10 myFrame = new NewFrame10();
myFrame.setSize(600, 400);
myFrame.setLocationRelativeTo(null);
myFrame.setTitle("窗体标题");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
}
参考链接:
https://www.bilibili.com/video/BV1JB4y1u7sM?p=34
JavaSwing创建一颗简单的树JTree 二