當前位置:首頁 » 編程語言 » java樹狀

java樹狀

發布時間: 2022-04-15 11:11:35

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怎麼設置樹狀列表使得其默認為展開

  1. 樹狀列表一般都是動態生成的(java後台實現),所以java只負責發送這些html代碼,而頁面控制就要交給前端的js來控制

  2. 所以要設置列表默認展開,只要把該區域的div設置為非隱藏即可

  3. 也可以使用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進行簡單的二叉樹實現,另有遍歷,當然遍歷是自然順序。

//如有需要請自行修改吧。

熱點內容
怎麼配置釘釘代理網路 發布:2025-01-21 07:17:16 瀏覽:710
固態硬碟緩存系統 發布:2025-01-21 07:15:05 瀏覽:350
修改linuxroot密碼 發布:2025-01-21 07:10:00 瀏覽:782
命題庫文件夾 發布:2025-01-21 07:09:53 瀏覽:160
壁紙老是變大怎麼辦安卓 發布:2025-01-21 07:09:14 瀏覽:662
卡爾頓麵包腳本策劃 發布:2025-01-21 06:34:45 瀏覽:264
界面像電腦一樣的伺服器 發布:2025-01-21 06:29:52 瀏覽:990
匿名祝福源碼 發布:2025-01-21 06:29:13 瀏覽:349
雲識別系統登陸密碼是多少 發布:2025-01-21 06:23:39 瀏覽:369
stl源碼剖析中文 發布:2025-01-21 06:14:17 瀏覽:345