我使用了orgchart图,先把数据生成xml格式,然后前台使用mxgraph去读取这个路径下的文件,就可以生成图形了,画图的代码都是按照orgchart来的!
1,首先将数据生成xml代码,格式要付个mxgraph定义的格式
@SkipValidation
public String findareaListforchart(){
List<Areas> list = new ArrayList<Areas>();
try {
UserVO userVO = (UserVO) getSession().get(Constants.SESSION_USER);
list= areaManageFacade.findareaListforchart(userVO);
} catch (Exception e) {
e.printStackTrace();
}
//定义areacode,存储上级变量
String areaCode = "";
//定义文件路径
String path = "D:\\tomcat\\webapps\\itmms\\example";
//判断文件是否存在,存在则删除并重新生成;不存在则直接生成(不予考虑),正常情况下文件应该存在
File file = new File(path);
Boolean bool = false;//判断文件是否删除成功
if (file.isDirectory()) {
//获取该目录下所有文件
File[] f = file.listFiles();
if (f.length > 0) {
//存在,则删除
for (int i = 0; i < f.length; i++) {
//判断文件或路径,进行删除F:\tools\tomcat\webapps\itmms\example
System.out.println(f[i].toString());
if (f[i].isFile() && f[i].exists() && f[i].toString().equals("D:\\tomcat\\webapps\\itmms\\example\\orgchart.xml")) {
bool = f[i].delete();
}
}
}
}
List<PTreeNode> treeNodeList = new ArrayList<PTreeNode>();
if (list != null && !list.isEmpty()) {
for (int i = 0; i < list.size(); i++) {
PTreeNode node = new PTreeNode();
node.setId(list.get(i).getAreaCode());
node.setText(list.get(i).getAreaName());
node.setParentId(list.get(i).getParentAreaId().toString());
List<PTreeNode> childList = new ArrayList<PTreeNode>();
childList = areaManageFacade.findByparentIdForchildren(node.getId());
if (childList !=null && !childList.isEmpty()) {
node.setChildren(childList);
}
treeNodeList.add(node);
}
}
Element mxGraphModel = new Element("mxGraphModel");
Document doc = new Document(mxGraphModel);//添加到文档中
Element root = new Element("root");
mxGraphModel.addContent(root);
Element mxCell = new Element("mxCell");
mxCell.setAttribute("id","0");
root.addContent(mxCell);
Element mxp = new Element("mxCell");
mxp.setAttribute("id","1");
mxp.setAttribute("parent","0");
root.addContent(mxp);//添加到节点
for(int i = 0 ; i < treeNodeList.size() ; i ++){
int m = 0;//作为互相引用的id变量
if (treeNodeList.get(i).getId().toString().equals("101")) {
//顶级节点
Element firstNode = new Element("mxCell");
firstNode.setAttribute("id",treeNodeList.get(i).getId());
firstNode.setAttribute("value",treeNodeList.get(i).getText());
firstNode.setAttribute("style","image=editors/images/house.png");
firstNode.setAttribute("vertex","1");
firstNode.setAttribute("parent","1");
Element firstNodeOne = new Element("mxGeometry");
firstNodeOne.setAttribute("x","640");
firstNodeOne.setAttribute("y","176");
firstNodeOne.setAttribute("width","120");
firstNodeOne.setAttribute("height","80");
firstNodeOne.setAttribute("as","geometry");
firstNode.addContent(firstNodeOne);
root.addContent(firstNode);
}else{
//子集节点
Element secondNode = new Element("mxCell");
secondNode.setAttribute("id",treeNodeList.get(i).getId());
secondNode.setAttribute("value",treeNodeList.get(i).getText());
secondNode.setAttribute("vertex","1");
secondNode.setAttribute("parent","1");
//定义坐标
Element secondNodeOne = new Element("mxGeometry");
secondNodeOne.setAttribute("x","640");
secondNodeOne.setAttribute("y","176");
secondNodeOne.setAttribute("width","120");
secondNodeOne.setAttribute("height","80");
secondNodeOne.setAttribute("as","geometry");
secondNode.addContent(secondNodeOne);
root.addContent(secondNode);
//定义关联关系
Element secondPosition = new Element("mxCell");
secondPosition.setAttribute("id",treeNodeList.get(i).getId()+"po");
secondPosition.setAttribute("value","");
secondPosition.setAttribute("edge","1");
secondPosition.setAttribute("parent","1");
secondPosition.setAttribute("source",treeNodeList.get(i).getParentId());
secondPosition.setAttribute("target",treeNodeList.get(i).getId());
Element secondPositionOne = new Element("mxGeometry");
secondPositionOne.setAttribute("x","1");
secondPositionOne.setAttribute("relative","1");
secondPositionOne.setAttribute("as","geometry");
Element mxpoint = new Element("mxPoint");
mxpoint.setAttribute("y","-20");
mxpoint.setAttribute("as","offset");
secondPositionOne.addContent(mxpoint);
secondPosition.addContent(secondPositionOne);
root.addContent(secondPosition);
}
}
//输出文件
XMLOutputter xmlout = new XMLOutputter();
try {
// xmlout.output(doc, new FileOutputStream("F:\\analyzeXML\\orgchart.xml"));
xmlout.output(doc, new FileOutputStream("D:\\tomcat\\webapps\\itmms\\example\\orgchart.xml"));
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
将数据生成xml,我的数据的格式我就在这里我就截取个图片了大家可以看一下:
数据生成xml,路径可以自行定义,我的路径是example这个文件夹下了!
2,读取xml,生成orgchart图形,代码如下:
<%@page contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
orgchart
</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<script type="text/javascript">
mxBasePath = '../src';
</script>
<script type="text/javascript" src="../src/js/mxClient.js"></script>
<script type="text/javascript" src="lhgdialog/lhgcore.lhgdialog.min.js"></script>
<script type="text/javascript">
//定义变量进行传值
var path = $.dialog.setting.path;
mxConstants.SHADOWCOLOR = '#C0C0C0';
//定义时间戳,用来防止加载缓存xml文件
var myDate=new Date().getTime();
function main(container){
//Checks if browser is supported
if(!mxClient.isBrowserSupported()){
//ä¸æ”¯æŒåˆ™è¿›è¡Œæ示
mxUtils.error('Browser is not supported!',200,false);
}else{
//创建图形
var container = document.createElement('div');
container.style.position = 'absolute';
container.style.overflow = 'hidden';
container.style.left = '0px';
container.style.top = '0px';
container.style.right = '0px';
container.style.bottom = '0px';
var outline = document.getElementById('outlineContainer');
mxEvent.disableContextMenu(container);
if (mxClient.IS_IE)
{
new mxDivResizer(container);
//æ— æ³•åˆ›å»ºoutline
// new mxDivResizer(outline);
}
// Sets a gradient background
if (mxClient.IS_GC || mxClient.IS_SF)
{
container.style.background = '-webkit-gradient(linear, 0 0%, 0% 100%, from(#FFFFFF), to(#E7E7E7))';
}
else if (mxClient.IS_NS)
{
container.style.background = '-moz-linear-gradient(top, #FFFFFF, #E7E7E7)';
}
else if (mxClient.IS_IE)
{
container.style.filter = 'progid:DXImageTransform.Microsoft.Gradient('+
'StartColorStr=\'#FFFFFF\', EndColorStr=\'#E7E7E7\', GradientType=0)';
}
document.body.appendChild(container);
var graph = new mxGraph(container);
var outln = new mxOutline(graph, outline);
graph.setTooltips(!mxClient.IS_TOUCH);
var style = graph.getStylesheet().getDefaultVertexStyle();
style[mxConstants.STYLE_SHAPE] = 'label';
style[mxConstants.STYLE_VERTICAL_ALIGN] = mxConstants.ALIGN_MIDDLE;
style[mxConstants.STYLE_ALIGN] = mxConstants.ALIGN_LEFT;
style[mxConstants.STYLE_SPACING_LEFT] = 40;
style[mxConstants.STYLE_GRADIENTCOLOR] = '#7d85df';
style[mxConstants.STYLE_STROKECOLOR] = '#5d65df';
style[mxConstants.STYLE_FILLCOLOR] = '#adc5ff';
style[mxConstants.STYLE_FONTCOLOR] = '#1d258f';
style[mxConstants.STYLE_FONTFAMILY] = 'Verdana';
style[mxConstants.STYLE_FONTSIZE] = '14';
style[mxConstants.STYLE_FONTSTYLE] = '1';
style[mxConstants.STYLE_SHADOW] = '1';
style[mxConstants.STYLE_ROUNDED] = '1';
style[mxConstants.STYLE_GLASS] = '1';
style[mxConstants.STYLE_IMAGE] = 'editors/images/dude3.png';
style[mxConstants.STYLE_IMAGE_WIDTH] = '20';
style[mxConstants.STYLE_IMAGE_HEIGHT] = '20';
style[mxConstants.STYLE_SPACING] = 2;
// 修改默认连接线样式
style = graph.getStylesheet().getDefaultEdgeStyle();
style[mxConstants.STYLE_ROUNDED] = true;
style[mxConstants.STYLE_STROKEWIDTH] = 3;
style[mxConstants.STYLE_EXIT_X] = 0.5; // center
style[mxConstants.STYLE_EXIT_Y] = 1.0; // bottom
style[mxConstants.STYLE_EXIT_PERIMETER] = 0; // disabled
style[mxConstants.STYLE_ENTRY_X] = 0.5; // center
style[mxConstants.STYLE_ENTRY_Y] = 0; // top
style[mxConstants.STYLE_ENTRY_PERIMETER] = 0; // disabled
//禁用以下几个为直线
style[mxConstants.STYLE_EDGE] = mxEdgeStyle.TopToBottom;
//禁止拖动流程线
graph.setCellsMovable(false);
//元素大小自动变化
graph.setAutoSizeCells(true);
graph.setPanning(true);
graph.panningHandler.useLeftButtonForPanning = true;
// 右键点击元素时显示下拉菜单
// 右键点击非元素的背景时显示另外一种菜单 •
graph.panningHandler.selectOnPopup = false;
//创建大纲
graph.panningHandler.selectOnPopup = true;
var keyHandler = new mxKeyHandler(graph);
var layout = new mxCompactTreeLayout(graph, false);
layout.useBoundingBox = false;
layout.edgeRouting = false;
layout.levelDistance = 60;
layout.nodeDistance = 16;
// 启用元素向下移动
layout.isVertexMovable = function(cell)
{
return true;
};
var layoutMgr = new mxLayoutManager(graph);
layoutMgr.getLayout = function(cell)
{
if (cell.getChildCount() > 0)
{
return layout;
}
};
// 创建右键下拉菜单
graph.panningHandler.factoryMethod = function(menu, cell, evt)
{
return createPopupMenu(graph, menu, cell, evt);
};
//修正首选大小的错误
var oldGetPreferredSizeForCell = graph.getPreferredSizeForCell;
graph.getPreferredSizeForCell = function(cell)
{
var result = oldGetPreferredSizeForCell.apply(this, arguments);
if (result != null)
{
result.width = Math.max(120, result.width - 40);
}
return result;
};
graph.setCellsSelectable(false);
graph.isCellFoldable = function(cell)
{
return this.model.getOutgoingEdges(cell).length > 0;
};
//开启更新事物
graph.foldCells = function(collapse, recurse, cells)
{
this.model.beginUpdate();
try
{
toggleSubtree(this, cells[0], !collapse);
this.model.setCollapsed(cells[0], collapse);
layout.execute(graph.getDefaultParent());
}
finally
{
//结束事物更新
this.model.endUpdate();
}
};
var parent = graph.getDefaultParent();
graph.getModel().beginUpdate();
graph.getModel().beginUpdate();
try
{
var w = graph.container.offsetWidth;
var v1 = graph.insertVertex(parent, 'treeRoot',
'Organization', w/2 - 30, 20, 140, 60, 'image=editors/images/house.png');
graph.updateCellSize(v1);
//addOverlays(graph, v1, false);
}
finally
{
// Updates the display
graph.getModel().endUpdate();
}
try{
var w = graph.container.offsetWidth;
read(graph,'orgchart.xml?m='+myDate);
}
finally
{
graph.getModel().endUpdate();
}
var content = document.createElement('div');
content.style.padding = '4px';
var tb = new mxToolbar(content);
tb.addItem('Zoom In','images/zoom_in32.png',function(evt){
graph.zoomIn();
});
tb.addItem('Zoom Out', 'images/zoom_out32.png',function(evt){
graph.zoomOut();
});
tb.addItem('Actual Size', 'images/view_1_132.png',function(evt)
{
graph.zoomActual();
});
tb.addItem('Fit','images/view_1.png',function(){
graph.fit();
});
wnd = new mxWindow('Tools', content, 0, 0, 200, 66, false);
wnd.setMaximizable(false);
wnd.setScrollable(false);
wnd.setResizable(false);
wnd.setVisible(true);
//åŒå‡»äº‹ä»¶
graph.dblClick = function(evt, cell)
{
var mxe = new mxEventObject(mxEvent.DOUBLE_CLICK, 'event', evt, 'cell', cell);
this.fireEvent(mxe);
if (this.isEnabled() &&
!mxEvent.isConsumed(evt) &&
!mxe.isConsumed() &&
cell != null)
{
// mxUtils.alert('Show properties for cell '+(cell.customId || cell.getId()));
//å‘é€ajax请求,查询当å‰area_code下é¢çš„所有网关
//alert((cell.customId || cell.getId()));
//window.open("findAllGateway.action?arecode="+(cell.customId || cell.getId()));
$.dialog({
title:'区域分析',
content: 'url:../example/findyiqiByAreaCode.action?queryAreaCode='+(cell.customId || cell.getId()),
width :'400px',
height : 250,
min : false,//去掉最小化
max : false,//去掉最大化
lockScroll : true,//添加遮罩层
init:function(){
//this.content.document.getElementById('txt1').value = (cell.customId || cell.getId());
}
});
}
};
if (mxClient.IS_QUIRKS)
{
document.body.style.overflow = 'hidden';
new mxDivResizer(container);
}
}
};
// 解æžmxGraph XMLæ–‡ä»¶æ ¼å¼
function read(graph, filename)
{
var req = mxUtils.load(filename);
var root = req.getDocumentElement();
var dec = new mxCodec(root.ownerDocument);
dec.decode(root, graph.getModel());
};
//æ·»åŠ æ”¶ç¼©äº‹ä»¶
function toggleSubtree(graph, cell, show)
{
show = (show != null) ? show : true;
var cells = [];
graph.traverse(cell, true, function(vertex)
{
if (vertex != cell)
{
cells.push(vertex);
}
// Stops recursion if a collapsed cell is seen
return vertex == cell || !graph.isCellCollapsed(vertex);
});
graph.toggleCells(show, cells, true);
};
function createPopupMenu(graph, menu, cell, evt)
{
var model = graph.getModel();
menu.addItem('Fit', 'editors/images/zoom.gif', function()
{
graph.fit();
});
menu.addItem('Actual', 'editors/images/zoomactual.gif', function()
{
graph.zoomActual();
});
menu.addSeparator();
};
</script>
</head>
<body οnlοad="main(document.getElementById('graphContainer'))" style="margin:4px;">
<div id="graphContainer" style="position:absolute;overflow:auto;top:36px;bottom:0px;left:0px;right:0px;border-top:gray 1px solid;">
</div>
</body>
</html>
ok,这样图形就可以生成了,这是两块最主要的代码,其他的如查询数据,大家可以按照自己的想法来,我在这里就不写了!本人没有写文章的天份,小时候一直作文不及格,只好贴代码了,如果有朋友需要的话,可以去http://download.csdn.net/my下载 ,里面是破解的mxgraph以及我自己研究的orgchart图形!我已经在我的资源里面上传了!
在这里再次进行说明一下:mxgraph是收费的,用于商业用途的话大约20w大红票,小项目不敢用啊 !四川的一家公司代理的!