JGraph分析
Johnny.Deng
JGraph是一個開源的,兼容Swing的基于MVC體系結構圖形組件,具有以下特點:
1) 完全Swing兼容;
2) 簡單、高效的設計;
3) 時間效率高;
4) 100 %純java;
生成的圖例
二、JGraph設計
1) MVC
Swing是Java(Sun)提供的UI標準實現之一,Swing基于AWT(Abstract Windowing Toolkit)。JGraph完全兼容Swing,它的實現仍然基于MVC體系結構。
JGraph MVC
View:
JGraph不包含實際的數據,它提供了數據的視;JGraph對象畫圖的機制是:
將圖元定義為一個一個的cell,每個cell可以是一個頂點(vertex)、邊(edge)或者節點(port)中的一種。頂點可以有鄰接的頂點,他們通過邊相聯系,邊聯接的兩個端點稱為目標和源,每個目標或者源是一個節點。節點是頂點的孩子。每個cell都可以有自己的孩子。
每個cell的外觀由相應的屬性定義,屬性序列是指一系列的鍵-值對,他們以Map形式組織,例如:
Map cellAttrib = new Hashtable();
// Set bounds
Rectangle2D helloBounds = new Rectangle2D.Double(20, 20, 40, 20);
GraphConstants.setBounds(cellAttrib, helloBounds);
// Set black border
GraphConstants.setBorderColor(cellAttrib, Color.black);
一個cell有類似這樣一個cellAttrib的Map,來定義其外觀。
外觀可以指定諸如一條邊的箭頭樣式等屬性。
Model:
數據對象可以看成是JGraph中兩個獨立結構的鏈接點:grahp結構和group結構。Graph結構基于圖論中的頂點、邊定義。Group結構是cell的composition結構。Graph結構中getSource()和getTarget()方法,獲得源和目標節點。而在group中通過getChild(),getParent()來獲得cell的組成結構。
2) 低層基于圖論邏輯
即:一個圖G包含一個非空的元素集V(G)和一個E(G),其中,E(G)是V(G)中兩個無序元素組成的二元組。V(G)稱為圖G頂點的集合,假如任意集合V(G)中的頂點x/y,(x,y)在E(G)中,邊(x,y)可能以連接頂點x和y的邊(?。┧?,X與y就被稱為鄰接的,否則x與y不鄰接。
三、JGraph的應用
以下是一個基于JGraph的Helloworld的分析:
import省略
public class HelloWorld {
public static void main(String[] args) {
// ConstrUCt Model and Graph
//
GraphModel model = new DefaultGraphModel();
JGraph graph = new JGraph(model);
graph.setSelectNewCells(true);
// Create Nested Map (from Cells to Attributes)
// 此Map中記錄所有屬性,其中的鍵-值對是cell-cellAttribute
// 每個cellAttribute又是一個Map,其鍵-值對是具體一個cell的屬性-值
Map attributes = new Hashtable();
// 以下建立兩個頂點(cell)Hello和World,并分別設置他們的屬性Map
// Create Hello Vertex
//
DefaultGraphCell hello = new DefaultGraphCell("Hello");
// Create Hello Vertex Attributes
//
Map helloAttrib = new Hashtable();
attributes.put(hello, helloAttrib);
// Set bounds
Rectangle2D helloBounds = new Rectangle2D.Double(20, 20, 40, 20);
GraphConstants.setBounds(helloAttrib, helloBounds);
// Set black border
GraphConstants.setBorderColor(helloAttrib, Color.black);
// Add a Port
// 每個頂點為了與其他頂點相鄰接,必須添加節點(cell)
DefaultPort hp = new DefaultPort();
hello.add(hp);
// Create World Vertex
//
DefaultGraphCell world = new DefaultGraphCell("World");
// Create World Vertex Attributes
//
Map worldAttrib = new Hashtable();
attributes.put(world, worldAttrib);
// Set bounds
Rectangle2D worldBounds = new Rectangle2D.Double(140, 140, 40, 20);
GraphConstants.setBounds(worldAttrib , worldBounds);
// Set fill color
GraphConstants.setBackground(worldAttrib, Color.orange);
GraphConstants.setOpaque(worldAttrib, true);
// Set raised border
GraphConstants.setBorder(worldAttrib,
BorderFactory.createRaisedBevelBorder());
// Add a Port
//
DefaultPort wp = new DefaultPort();
world.add(wp);
// 建立聯接兩個頂點的邊
新聞熱點
疑難解答