java树状
A. 如何用java实现树形结构啊
定义一个简单的菜单类 这里是简单的示例 你可以自行扩展package entity;import java.util.ArrayList;
import java.util.List;/**
* 菜单类
* @author Administrator
*
*/
public class Menu {
/**
* 菜单标题
*/
private String title;
/**
* 子菜单的集合
*/
private List<Menu> childs;
/**
* 父菜单
*/
private Menu parent;
/**
* 构造函数 初始化标题和子菜单集合
*/
public Menu(String title) {
this();
this.title=title;
}
/**
* 构造函数 创建一个虚拟的父菜单(零级菜单) 所有的一级菜单都归属于一个虚拟的零级菜单
*
*/
public Menu() {
this.childs = new ArrayList<Menu>();
}
/**
* 获取子菜单
* @return
*/
public List<Menu> getChilds() {
return childs;
}
/**
* 获取标题
* @return
*/
public String getTitle() {
return title;
}
/**
* 获取父菜单
* @return
*/
public Menu getParent() {
return parent;
}
/**
* 添加子菜单并返回该子菜单对象
* @param child
* @return
*/
public Menu addChild(Menu child){
this.childs.add(child);
return child;
}
/**
* 设置父菜单
* @param parent
*/
public void setParent(Menu parent) {
this.parent = parent;
}
/**
* 设置标题
* @param title
*/
public void setTitle(String title) {
this.title = title;
}
} 测试package entity;
/**
* 测试类
* @author Administrator
*
*/
public class Test { /**
* @param args
*/
public static void main(String[] args) {
/**
* 创建一个虚拟的父菜单 用于存放一级菜单 menu01 和 menu02
*/
Menu root = new Menu();
/**
* 创建两个一级菜单
*/
Menu menu01 = new Menu("一级菜单01");
Menu menu02 = new Menu("一级菜单02");
/**
* 加入虚拟菜单
*/
root.addChild(menu01);
root.addChild(menu02);
/**
* 为两个一级菜单分别添加两个子菜单 并返回该子菜单 需要进一步处理的时候 才接收返回的对象 否则只要调用方法
*/
Menu menu0101 = menu01.addChild(new Menu("二级菜单0101"));
menu01.addChild(new Menu("二级菜单0102"));
menu02.addChild(new Menu("二级菜单0201"));
Menu menu0202 = menu02.addChild(new Menu("二级菜单0202"));
/**
* 添加三级菜单
*/
menu0101.addChild(new Menu("三级菜单010101"));
menu0202.addChild(new Menu("三级菜单020201"));
/**
* 打印树形结构
*/
showMenu(root);
} /**
* 递归遍历某个菜单下的菜单树
*
* @param menu
* 根菜单
*/
private static void showMenu(Menu menu) {
for (Menu child : menu.getChilds()) {
showMenu(child, 0);
}
} private static void showMenu(Menu menu, int tabNum) {
for (int i = 0; i < tabNum; i++)
System.out.print("\t");
System.out.println(menu.getTitle());
for (Menu child : menu.getChilds())
// 递归调用
showMenu(child, tabNum + 1);
}}
控制台输出结果 一级菜单01 二级菜单0101
三级菜单010101
二级菜单0102一级菜单02
二级菜单0201
二级菜单0202
三级菜单020201
B. java 如何在JFrame中画出树状图
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
public class TreeEditTest {
public static void main(String[] args) {
JFrame frame = new TreeEditFrame();
frame.show();
}
}
class TreeEditFrame extends JFrame implements ActionListener {
public TreeEditFrame() {
setTitle("TreeEditTest");
setSize(300, 200);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// construct tree
TreeNode root = makeSampleTree();
model = new DefaultTreeModel(root);
tree = new JTree(model);
DefaultTreeCellRenderer renderer=new DefaultTreeCellRenderer();
renderer.setLeafIcon(new ImageIcon("1.gif"));
renderer.setClosedIcon(new ImageIcon("2.gif"));
renderer.setOpenIcon(new ImageIcon("3.gif"));
//renderer.(Color.BLUE);
//renderer.setBackgroundSelectionColor(Color.RED);
renderer.setBorderSelectionColor(Color.RED);
tree.setCellRenderer(renderer);
// add scroll pane with tree to content pane
Container contentPane = getContentPane();
JScrollPane scrollPane = new JScrollPane(tree);
contentPane.add(scrollPane, "Center");
// make button panel
JPanel panel = new JPanel();
addSiblingButton = new JButton("Add Sibling");
addSiblingButton.addActionListener(this);
panel.add(addSiblingButton);
addChildButton = new JButton("Add Child");
addChildButton.addActionListener(this);
panel.add(addChildButton);
deleteButton = new JButton("Delete");
deleteButton.addActionListener(this);
panel.add(deleteButton);
contentPane.add(panel, "South");
}
public TreeNode makeSampleTree() {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("World");
DefaultMutableTreeNode country = new DefaultMutableTreeNode("USA");
root.add(country);
DefaultMutableTreeNode state = new DefaultMutableTreeNode("California");
country.add(state);
DefaultMutableTreeNode city = new DefaultMutableTreeNode("San Jose");
state.add(city);
city = new DefaultMutableTreeNode("Cupertino");
state.add(city);
state = new DefaultMutableTreeNode("Michigan");
country.add(state);
city = new DefaultMutableTreeNode("Ann Arbor");
state.add(city);
country = new DefaultMutableTreeNode("Germany");
root.add(country);
state = new DefaultMutableTreeNode("Schleswig-Holstein");
country.add(state);
city = new DefaultMutableTreeNode("Kiel");
state.add(city);
return root;
}
public void actionPerformed(ActionEvent event) {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree
.getLastSelectedPathComponent();
if (selectedNode == null)
return;
if (event.getSource().equals(deleteButton)) {
if (selectedNode.getParent() != null)
model.removeNodeFromParent(selectedNode);
// model.removeFromParent(selectedNode);
return;
}
// add new node as sibling or child
DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New");
if (event.getSource().equals(addSiblingButton)) {
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode
.getParent();
if (parent != null) {
int selectedIndex = parent.getIndex(selectedNode);
model.insertNodeInto(newNode, parent, selectedIndex + 1);
}
} else if (event.getSource().equals(addChildButton)) {
model.insertNodeInto(newNode, selectedNode, selectedNode
.getChildCount());
}
// now display new node
TreeNode[] nodes = model.getPathToRoot(newNode);
TreePath path = new TreePath(nodes);
tree.scrollPathToVisible(path);
}
private DefaultTreeModel model;
private JTree tree;
private JButton addSiblingButton;
private JButton addChildButton;
private JButton deleteButton;
private JButton editButton;
}
http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/javax/swing/JTree.html
C. java使用递归实现树形结构
sql">
inserttb_menu(id,name,parent)(640000000000,北京市,0);
inserttb_menu(id,name,parent)(640100000000,昌平区,1);
inserttb_menu(id,name,parent)(640101000000,霍营,2);
inserttb_menu(id,name,parent)(640101001000,回龙观东大街,3);
添加一个节点属性, 根据数据不同代表的地位不同,0就代表父节点 ,1是0的子节点,2是1的子节点,以此类推。
D. java怎么设置树状列表使得其默认为展开
树状列表一般都是动态生成的(java后台实现),所以java只负责发送这些html代码,而页面控制就要交给前端的js来控制
所以要设置列表默认展开,只要把该区域的div设置为非隐藏即可
也可以使用js的一些类库来实现树状列表
E. java树形菜单编辑保存
在图形界面中添加文本框架实现文本编辑,通过鼠标菜单栏添加事件监听实现保存。
在开发中我们经常会遇到左边是树形菜单,右边是一个显示列表,单击左边的树形菜单项时,右边会显示该菜单里面相对应的内容。在实战开发中经常有需要处理树形菜单、树形目录等等等业务需求。
而对于这种产品,在设计数据库时也建议使用idparentId的结构来做。
F. 用java 生成一个树形菜单
packagecom.csii;
importjava.awt.GridLayout;
importjavax.swing.JEditorPane;
importjavax.swing.JFrame;
importjavax.swing.JPanel;
importjavax.swing.JScrollPane;
importjavax.swing.JTree;
importjavax.swing.SwingUtilities;
importjavax.swing.UIManager;
importjavax.swing.event.TreeSelectionEvent;
importjavax.swing.event.TreeSelectionListener;
importjavax.swing.tree.DefaultMutableTreeNode;
importjavax.swing.tree.TreeSelectionModel;
{
=1L;
privateJPaneljContentPane=null;
privateJTreejTree=null;
privateJEditorPanejEditorPane=null;
privateJScrollPanejScrollPane=null;
(){
if(jScrollPane==null){
jScrollPane=newJScrollPane();
jScrollPane.setViewportView(getJTree());
}
returnjScrollPane;
}
DefaultMutableTreeNodetop=null;//@jve:decl-index=0:
/**
*Thisisthedefaultconstructor
*/
publicTreeDemo1(){
super();
initialize();
}
/**
*Thismethodinitializesthis
*
*@returnvoid
*/
privatevoidinitialize(){
this.setSize(438,309);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(getJContentPane());
this.setTitle("JFrame");
}
/**
*
*
*@returnjavax.swing.JPanel
*/
privateJPanelgetJContentPane(){
if(jContentPane==null){
GridLayoutgridLayout=newGridLayout();
gridLayout.setRows(1);
gridLayout.setColumns(2);
jContentPane=newJPanel();
jContentPane.setLayout(gridLayout);
jContentPane.add(getjScrollPane(),null);
jContentPane.add(getJEditorPane(),null);
}
returnjContentPane;
}
/**
*ThismethodinitializesjTree
*
*@returnjavax.swing.JTree
*/
privateJTreegetJTree(){
if(jTree==null){
top=newDefaultMutableTreeNode("黄山");
createNodes(top);
jTree=newJTree(top);
jTree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION);
jTree.addTreeSelectionListener(this);
}
returnjTree;
}
privatevoidcreateNodes(DefaultMutableTreeNodetop){
=null,jiaotong=null,zhusu=null,binguan=null,luying=null,jiesu=null;
jingdian=newDefaultMutableTreeNode("景点");
jingdian.add(newDefaultMutableTreeNode("景点1"));
jingdian.add(newDefaultMutableTreeNode("景点2"));
jiaotong=newDefaultMutableTreeNode("交通");
jiaotong.add(newDefaultMutableTreeNode("路线1"));
jiaotong.add(newDefaultMutableTreeNode("路线2"));
jiaotong.add(newDefaultMutableTreeNode("路线3"));
zhusu=newDefaultMutableTreeNode("住宿");
zhusu.add(newDefaultMutableTreeNode("A住宿"));
zhusu.add(newDefaultMutableTreeNode("B住宿"));
zhusu.add(newDefaultMutableTreeNode("C住宿"));
binguan=newDefaultMutableTreeNode("宾馆");
binguan.add(newDefaultMutableTreeNode("X宾馆"));
binguan.add(newDefaultMutableTreeNode("Y宾馆"));
binguan.add(newDefaultMutableTreeNode("Z宾馆"));
binguan.add(newDefaultMutableTreeNode("XYZ宾馆"));
luying=newDefaultMutableTreeNode("露营");
luying.add(newDefaultMutableTreeNode("方式1"));
luying.add(newDefaultMutableTreeNode("方式2"));
jiesu=newDefaultMutableTreeNode("借宿");
jiesu.add(newDefaultMutableTreeNode("借宿1"));
jiesu.add(newDefaultMutableTreeNode("借宿2"));
jiesu.add(newDefaultMutableTreeNode("借宿3"));
top.add(jingdian);
top.add(jiaotong);
top.add(zhusu);
top.add(binguan);
top.add(luying);
top.add(jiesu);
}
/**
*
*
*@returnjavax.swing.JEditorPane
*/
(){
if(jEditorPane==null){
jEditorPane=newJEditorPane();
}
returnjEditorPane;
}
@Override
publicvoidvalueChanged(TreeSelectionEvente){
DefaultMutableTreeNodenode=(DefaultMutableTreeNode)jTree
.getLastSelectedPathComponent();
if(node==null)
//Nothingisselected.
return;
if(node.isRoot()){
jEditorPane.setText("黄山的简介");
}
}
publicstaticvoidmain(String[]args){
SwingUtilities.invokeLater(newRunnable(){
@Override
publicvoidrun(){
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exceptione){
e.printStackTrace();
}
newTreeDemo1().setVisible(true);
}
});
}
}
G. java树状菜单表怎么设置页面
树状列表一般都是动态生成的(java后台实现),所以java只负责发送这些html代码,而页面控制就要交给前端的js来控制所以要设置列表默认,只要把该区域的div设置为非隐藏即可也可以使用js的一些类库来实现树状列表
H. 请问这个树状图在Java中应该怎么做
打个比方
可以写一个Tree的类
public class Tree extends BaseDomain {private String id;
private String key;
private String icon;
private String title;
private String value;
private String text;
private String code;
private String mtype;
private String type;
/**
* 部门的特殊个别字段
* 1.部门 / 2.岗位 的编码
*/
private String number;
private Double order;
private Double sort;
private String href;
private String component;
private List<Tree<T>> children;
private String parentId;
private boolean hasParent = false;
private boolean hasChildren = false;
private Date createTime;
private Date modifyTime;
public void initChildren(){
this.children = new ArrayList<>();
}
}
在写一个工具类
public class TreeUtil {
protected TreeUtil() {
}
private final static String TOP_NODE_ID = "0";
/**
* 用于构建菜单
*
* @param nodes nodes
* @param <T> <T>
* @return <T> Tree<T>
*/
public static <T> Tree<T> build(List<Tree<T>> nodes) {
if (nodes == null) {
return null;
}
List<Tree<T>> topNodes = new ArrayList<>();
nodes.forEach(node -> {
String pid = node.getParentId();
if (pid == null || TOP_NODE_ID.equals(pid)) {
topNodes.add(node);
return;
}
for (Tree<T> n : nodes) {
String id = n.getId();
if (id != null && id.equals(pid)) {
if (n.getChildren() == null)
n.initChildren();
n.getChildren().add(node);
node.setHasParent(true);
n.setHasChildren(true);
n.setHasParent(true);
return;
}
}
if (topNodes.isEmpty())
topNodes.add(node);
});
Tree<T> root = new Tree<>();
root.setId("0");
root.setParentId("");
root.setHasParent(false);
root.setHasChildren(true);
root.setChildren(topNodes);
root.setText("root");
return root;
}}
写完了这两个在写业务层
一个构建书的方法
private void buildTrees(List> trees, List menus, List ids) {
menus.forEach(menu -> {
ids.add(menu.getId().toString());
Tree tree = new Tree<>();
tree.setId(menu.getId().toString());
tree.setKey(tree.getId());
tree.setParentId(menu.getParentId().toString());
tree.setText(menu.getName());
tree.setTitle(tree.getText());
tree.setIcon(menu.getIcon());
tree.setComponent(menu.getComponent());
tree.setCreateTime(menu.getCreateTime());
tree.setCreateTime(menu.getCreateTime());
tree.setHref(menu.getHref());
tree.setSort(menu.getSort());
tree.setCode(menu.getCode());
tree.setMtype(menu.getMtype());
trees.add(tree);
});
}Map<String, Object> result = new HashMap<>();
List<Dept> depts = findDepts(dept, request);
List<Tree<Dept>> trees = new ArrayList<>();
buildTrees(trees, depts);
Tree<Dept> deptTree = TreeUtil.build(trees);
result.put("rows", deptTree);
result.put("total", depts.size());
I. Java、实现树状菜单,谁能给我小例子
根据ID、父ID来排序的JS树
// 得到接点
var datas = sFileName.selectNodes("datas/data") ;
var list = new Array() ;
var data = new Array() ;
for( var i = 0 ; i < datas.length ; i++ ){
if( datas[i].getAttribute( "类型" ) == "文件夹" ){
list.push( datas[i] ) ;
} else {
data.push( datas[i] ) ;
}
}
// 设置初始的父号
var fatherNo = -1 ;
// 显示目录
showTreeList( tree , fatherNo , datas ,list , data , null ,"") ;
// 改变图片和隐藏显示DIV
function expand( div , img ){
if( div.style.display == "block" ){
div.style.display = "none" ;
img.src = "images/pic/skin_NLine/closed.gif" ;
} else {
div.style.display = "block" ;
img.src = "images/pic/skin_NLine/opened.gif" ;
}
}
// 递归显示树
function showTreeList( tree , fatherNo , datas ,list , data , currentNode , listStrblank2 ) {
// 创建一个DIV
var treediv = document.createElement("div");
var isdisplay = "1" //节点的状态 默认为显示状态
treediv.id = "treediv" + isdisplay + fatherNo ;
if( currentNode ){
tree.innerHTML += listStrblank2 + "<IMG SRC='images/pic/skin_NLine/opened.gif' onclick='expand(" + treediv.id + ",this)' />" + currentNode.getAttribute( "组名称" ) + "<br>" ;
}
treediv.style.display = "block";
document.getElementById("MonitorObject").appendChild( treediv );
// 如果currentNode存在则显示组名称
var l = isChildList( fatherNo , list ) ;
// 如果有子目录,则在次循环.没有则判断是否有信息
if( l.length != 0 ){
listStrblank2 += " " ;
for( var j = 0 ; j < l.length ; j++ ){
showTreeList( treediv , l[j].getAttribute( "id" ) , datas ,list , data , l[j] , listStrblank2 ) ;
}
}
var d = isChildData( fatherNo , data ) ;
// 如果有子信息,则在次循环.没有则判断是否有信息
if( d.length != 0 ){
for( var j = 0 ; j < d.length ; j++ ) {
treediv.innerHTML += listStrblank2 + "<IMG SRC='images/pic/people.png' /><input type='checkbox' name='pName' value='" + d[j].getAttribute( "对象属性" ) + "'>" + "美女" + "<br> " ;
}
}
tree.appendChild(treediv) ;
}
// 判断是否有子文件夹
function isChildList( fatherNo , lists ){
// 定义一个保存子目录的对象
var l = new Array() ;
// 循环找其子目录
for( var i = 0 ; i < lists.length ; i++ ) {
// 如果父编号和父号相同,则保存
if( lists[i].getAttribute( "父编号" ) == fatherNo ) {
l.push( lists[i] ) ;
}
}
return l ;
}
// 判断是否有子信息
function isChildData( fatherNo , datas ){
var d = new Array() ;
for( var i = 0 ; i < datas.length ; i++ ) {
if( datas[i].getAttribute( "父编号" ) == fatherNo ) {
d.push( datas[i] ) ;
//alert(datas[i].getAttribute( "对象属性" )) ;
}
}
return d ;
}
J. 用Java实现一个树形结构,并对其进行遍历
importjava.util.Iterator;
importjava.util.Random;
importjava.util.TreeSet;
publicclassDemo{
publicstaticvoidmain(String[]args)throwsException{
TreeSet<Integer>ts=newTreeSet<Integer>();
for(inti=0;i<10;i++){
ts.add(newRandom().nextInt(999));
}
for(Iterator<Integer>it=ts.iterator();it.hasNext();){
System.out.println(it.next());
}
}
}
//上面是利用TreeSet进行简单的二叉树实现,另有遍历,当然遍历是自然顺序。
//如有需要请自行修改吧。