Kalaimaan

Doing simple things to make great life

Archive for the ‘Java’ Category

Workout samples in Java environment

Patterns in JAVA (Design Patterns)

Posted by kalaimaan on February 11, 2009

Creational Patterns

Type of Patterns

1. Creational Patterns

  • The Factory Pattern

  • The Abstract Factory Pattern

  • The Singleton Pattern

  • The Builder Pattern

  • The Prototype Pattern

2. Structural Patterns

  • The Adapter Pattern

  • The Bridge Pattern

  • The Composite Pattern

  • The Decorator Pattern

  • The Façade Pattern

  • The Flyweight Pattern

  • The Proxy Pattern

3. Behavioral Patterns

  • The Command Pattern

  • The Interpreter Pattern

  • The Iterator Pattern

  • The Mediator Pattern

  • The Memento Pattern

  • The Observer Pattern

  • The State Pattern

  • The Strategy Pattern

  • The Template Pattern

  • The Visitor Pattern

Creational Patterns
All of the creational patterns deal with the best way to create instances of objects. This is important because your program should not depend on how objects are created and arranged. In Java, of course, the simplest way to create an instance of an object is by using the new operator.

Fred = new Fred(); //instance of Fred class

However, this really amounts to hard coding, depending on how you create the object within your program. In many cases, the exact nature of the object that is created could vary with the needs of the program and abstracting the creation process into a special “creator” class can make your program more flexible and general.

The Factory Method provides a simple decision making class that returns one of several possible subclasses of an abstract base class depending on the data that are provided.

The Abstract Factory Method provides an interface to create and return one of several families of related objects.

The Builder Pattern separates the construction of a complex object from its representation, so that several different representations can be created depending on the needs of the program.

The Prototype Pattern starts with an initialized and instantiated
class and copies or clones it to make new instances rather than creating new
instances.

The Singleton Pattern is a class of which there can be no more than
one instance. It provides a single global point of access to that instance.

Structural Patterns
Structural patterns describe how classes and objects can be combined to form larger structures. The difference between class patterns and object patterns is that class patterns describe how inheritance can be used to provide more useful program interfaces. Object patterns, on the other hand, describe how objects can be composed into larger structures using object composition, or the inclusion of objects within other objects.

The Adapter pattern, used to change the interface of one class to that of another one.

The Bridge pattern, intended to keep the interface to your client program constant while allowing you to change the actual kind of class you display or use. You can then change the interface and the underlying class separately.

The Composite pattern, a collection of objects, any one of which may be either itself a Composite, or just a primitive object.

The Decorator pattern, a class that surrounds a given class, adds new capabilities to it, and passes all the unchanged methods to the underlying class.

The Façade pattern, which groups a complex object hierarchy and provides a new, simpler interface to access those data.

The Flyweight pattern, which provides a way to limit the proliferation of small, similar class instances by moving some of the class data outside the class and passing it in during various execution methods.

The Proxy pattern, which provides a simple place-holder class for a more complex class which is expensive to instantiate.

Behavioral Patterns
Behavioral patterns are those patterns that are most specifically concerned with communication between objects.

The Observer pattern defines the way a number of classes can be notified of a change,

The Mediator defines how communication between classes can be simplified by using another class to keep all classes from having to know about each other. The Chain of Responsibility allows an even further decoupling between classes, by passing a request between classes until it is recognized.

The Template pattern provides an abstract definition of an algorithm.

The Interpreter provides a definition of how to include language elements in a program.

The Strategy pattern encapsulates an algorithm inside a class

The Visitor pattern adds function to a class

The State pattern provides a memory for a class’s instance variables.

The Command pattern provides a simple way to separate execution of a command from the interface environment that produced it.

The Iterator pattern formalizes the way we move through a list of data within a class.

Advertisements

Posted in Java, Patterns | Tagged: , , | Leave a Comment »

Add BPMN Events using JGraph, add icon in jgraph

Posted by kalaimaan on February 1, 2009

Hi Friends,

Here I like to post the details of BPMN designer ( Business process management notation). Here I posted the jgraph code to achieve the BPMN Event types

File details:

  • GraphViewer.java
  • EventsFactory.java
  • StartEvent.java
  • EndEvent.java
  • InterEvent.java
  • EventsType.java
  • EventDetails.java
  • BPMNType.java
  • BPMNEvent.java

1. GraphViewer.java

public class GraphViewer extends JFrame implements ActionListener

{

private JButton btnInsert = null;

private JButton btnDelete = null;

private JComboBox cbxEvent = null;

private JComboBox cbxObject = null;

public JGraph jGraph = null;

public DefaultGraphModel jGraphModel = null;

private static int id =0;

public GraphViewer()

{

super(“JGraph Demo-Kalaimaan”);

initGraph();

}

/**

*

*/

private void initGraph()

{

setLayout(new BorderLayout());

add(initNorthPanel(), BorderLayout.NORTH);

JScrollPane panel = new JScrollPane(initGraphPanel(),

JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,

JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

add(panel, BorderLayout.CENTER);

setVisible(true);

setSize(new Dimension(600, 600));

}

/**

*

* @return

*/

private JComponent initNorthPanel()

{

JPanel temp = new JPanel(new BorderLayout());

JPanel child = new JPanel();

cbxObject = new JComboBox();

cbxObject.setPreferredSize(new Dimension(100, 25));

child.add(cbxObject);

cbxObject.addItem(BPMNType.START);

cbxObject.addItem(BPMNType.INTER);

cbxObject.addItem(BPMNType.END);

JLabel lab = new JLabel(” With “);

child.add(lab);

cbxEvent = new JComboBox();

cbxEvent.setPreferredSize(new Dimension(150, 25));

child.add(cbxEvent);

cbxEvent.addItem(BPMNEvent.MessageIcon);

cbxEvent.addItem(BPMNEvent.CancelIcon);

cbxEvent.addItem(BPMNEvent.CompensationIcon);

cbxEvent.addItem(BPMNEvent.ErrorIcon);

cbxEvent.addItem(BPMNEvent.LinkIcon);

cbxEvent.addItem(BPMNEvent.MultipleIcon);

cbxEvent.addItem(BPMNEvent.RuleIcon);

cbxEvent.addItem(BPMNEvent.TerminateIcon);

cbxEvent.addItem(BPMNEvent.TimerIcon);

cbxEvent.addItem(BPMNEvent.None);

btnInsert = new JButton(“Insert”);

btnInsert.addActionListener(this);

btnInsert.setPreferredSize(new Dimension(100, 25));

child.add(btnInsert);

btnDelete = new JButton(“Delete”);

btnDelete.addActionListener(this);

btnDelete.setPreferredSize(new Dimension(100, 25));

child.add(btnDelete);

temp.add(child);

return temp;

}

private JComponent initGraphPanel()

{

jGraphModel = new DefaultGraphModel();

jGraph = new JGraph(jGraphModel);

jGraph.setGridColor(Color.lightGray);

jGraph.setGridMode(JGraph.LINE_GRID_MODE);

jGraph.setGridSize(20);

jGraph.setGridEnabled(true);

jGraph.setGridVisible(true);

jGraph.setHandleColor(Color.red);

jGraph.setSelectionEnabled(true);

jGraph.getGraphLayoutCache().setFactory(new EventsFactory());

return jGraph;

}

@Override

public void actionPerformed(ActionEvent e)

{

if (e.getActionCommand().equalsIgnoreCase(“Insert”))

insertEvents();

else if (e.getActionCommand().equalsIgnoreCase(“Delete”))

deleteEvents();

}

private void insertEvents()

{

BPMNType type = (BPMNType) cbxObject.getSelectedItem();

BPMNEvent eve = (BPMNEvent) cbxEvent.getSelectedItem();

EventDetails dt = null;

switch (type)

{

case START:

dt = new EventDetails(type,”Start”, getId(), eve);

break;

case INTER:

dt = new EventDetails(type,”Inter”, getId(), eve);

break;

case END:

dt = new EventDetails(type,”Inter”, getId(), eve);

break;

}

DefaultGraphCell cell = new DefaultGraphCell(dt);

cell.setAttributes(getEventsAttributes());

jGraph.getGraphLayoutCache().insert(cell);

}

private void deleteEvents()

{

jGraph.getGraphLayoutCache().remove(jGraph.getSelectionCells());

jGraph.clearOffscreen();

}

private AttributeMap getEventsAttributes()

{

AttributeMap map = new AttributeMap();

Rectangle2D cellRect = new Rectangle(20, 20, 60, 60);

GraphConstants.setBounds(map, cellRect);

GraphConstants.setConstrained(map, true);

GraphConstants.setSizeable(map, false);

GraphConstants.setVerticalAlignment(map, JLabel.BOTTOM);

GraphConstants.setVerticalTextPosition(map, JLabel.CENTER);

GraphConstants.setGradientColor(map, Color.yellow.brighter());

GraphConstants.setBorderColor(map, Color.black);

GraphConstants.setBackground(map, Color.white);

GraphConstants.setOpaque(map, true);

GraphConstants.setEditable(map, false);

GraphConstants.setSelectable(map, true);

return map;

}

private String getId()

{

return “” + id++;

}

public static void main(String[] args)

{

try

{

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

}

catch (Exception e)

{

e.printStackTrace();

}

GraphViewer viewer = new GraphViewer();

viewer.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

viewer.setVisible(true);

}

}

2. EventsFactory.java

public class EventsFactory extends DefaultCellViewFactory

{

public CellView createView(GraphModel model, Object cell)

{

CellView view = createVertexView(cell);

return view;

}

/**

*

*/

protected VertexView createVertexView(Object cell)

{

VertexView view = new VertexView(cell);

DefaultGraphCell graphCell = (DefaultGraphCell) cell;

EventDetails element = (EventDetails) graphCell.getUserObject();

if (element == null)

return view;

switch (element.getType())

{

case START:

view = new StartEvent(cell);

break;

case INTER:

view = new InterEvent(cell);

break;

case END:

view = new EndEvent(cell);

break;

}

return view;

}

}

3. StartEvent.java

public class StartEvent extends VertexView

{

public static EventsType eventTypes = new EventsType();

public static transient StartEventRenderer renderer = new StartEventRenderer();

public StartEvent()

{

super();

}

public StartEvent(Object cell)

{

super(cell);

}

public CellViewRenderer getRenderer()

{

return renderer;

}

public static class StartEventRenderer extends VertexRenderer

{

public void paint(Graphics g)

{

Graphics2D g2 = (Graphics2D) g;

Rectangle ovalRect = new Rectangle(1, 1, 39, 39);

if (super.isOpaque())

{

g2.setColor(super.getBackground());

if (gradientColor != null && !preview)

{

setOpaque(false);

g2.setPaint(new GradientPaint(0, 0, getBackground(), getWidth(), getHeight(),

gradientColor, true));

}

g2.fillOval(ovalRect.x, ovalRect.y, ovalRect.width, ovalRect.height);

}

setBorder(null);

setOpaque(false);

Stroke old = g2.getStroke();

if (bordercolor != null)

{

g2.setColor(bordercolor);

g2.setStroke(new BasicStroke(1.7f));

g2.drawOval(ovalRect.x, ovalRect.y, ovalRect.width, ovalRect.height);

g2.setStroke(old);

// set the event types..

EventDetails det = (EventDetails)((DefaultGraphCell)view.getCell()).getUserObject();

switch (det.getEvent())

{

case MessageIcon:

eventTypes.paintMessageIcon(g);

break;

case TimerIcon:

eventTypes.paintTimerIcon(g);

break;

case ErrorIcon:

eventTypes.paintErrorIcon(g);

break;

case CancelIcon:

eventTypes.paintCancelIcon(g);

break;

case CompensationIcon:

eventTypes.paintCompensationIcon(g);

break;

case RuleIcon:

eventTypes.paintRuleIcon(g);

break;

case LinkIcon:

eventTypes.paintLinkIcon(g);

break;

case TerminateIcon:

eventTypes.paintTerminateIcon(g);

break;

case MultipleIcon:

eventTypes.paintMultipleIcon(g);

break;

}

}

if (selected)

{

g2.setStroke(GraphConstants.SELECTION_STROKE);

g2.setColor(defaultBackground);

g2.setStroke(new BasicStroke(1.9f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,

10.0f, new float[] { 5f, 5f }, 0.0f));

g2.drawOval(ovalRect.x, ovalRect.y, ovalRect.width, ovalRect.height);

}

super.paint(g2);

}

}

}

4. EndEvent.java

public class EndEvent extends VertexView

{

public static EventsType eventTypes = new EventsType();

public static transient EndEventRenderer renderer = new EndEventRenderer();

public EndEvent()

{

super();

}

public EndEvent(Object cell)

{

super(cell);

}

public CellViewRenderer getRenderer()

{

return renderer;

}

public static class EndEventRenderer extends VertexRenderer

{

public void paint(Graphics g)

{

Graphics2D g2 = (Graphics2D) g;

Rectangle ovalRect = new Rectangle(2, 2, 36, 36);

if (super.isOpaque())

{

g2.setColor(super.getBackground());

if (gradientColor != null && !preview)

{

setOpaque(false);

g2.setPaint(new GradientPaint(0, 0, getBackground(), getWidth(), getHeight(),

gradientColor, true));

}

g2.fillOval(ovalRect.x, ovalRect.y, ovalRect.width, ovalRect.height);

}

setBorder(null);

setOpaque(false);

Stroke old = g2.getStroke();

if (bordercolor != null)

{

g2.setColor(bordercolor);

g2.setStroke(new BasicStroke(4f));

g2.drawOval(ovalRect.x, ovalRect.y, ovalRect.width, ovalRect.height);

g2.setStroke(old);

EventDetails det = (EventDetails)((DefaultGraphCell)view.getCell()).getUserObject();

switch (det.getEvent())

{

case MessageIcon:

eventTypes.paintMessageIcon(g);

break;

case TimerIcon:

eventTypes.paintTimerIcon(g);

break;

case ErrorIcon:

eventTypes.paintErrorIcon(g);

break;

case CancelIcon:

eventTypes.paintCancelIcon(g);

break;

case CompensationIcon:

eventTypes.paintCompensationIcon(g);

break;

case RuleIcon:

eventTypes.paintRuleIcon(g);

break;

case LinkIcon:

eventTypes.paintLinkIcon(g);

break;

case TerminateIcon:

eventTypes.paintTerminateIcon(g);

break;

case MultipleIcon:

eventTypes.paintMultipleIcon(g);

break;

}

}

if (selected)

{

g2.setStroke(GraphConstants.SELECTION_STROKE);

g2.setColor(defaultBackground);

g2.setStroke(new BasicStroke(4.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,

10.0f, new float[] { 5f, 5f }, 0.0f));

g2.drawOval(ovalRect.x, ovalRect.y, ovalRect.width, ovalRect.height);

g2.setStroke(old);

}

super.paint(g2);

}

}

}

5. InterEvent.java

public class InterEvent extends VertexView

{

public static EventsType eventTypes = new EventsType();

public static transient InterEventRenderer renderer = new InterEventRenderer();

public InterEvent()

{

super();

}

public InterEvent(Object cell)

{

super(cell);

}

public CellViewRenderer getRenderer()

{

return renderer;

}

public static class InterEventRenderer extends VertexRenderer

{

public void paint(Graphics g)

{

Graphics2D g2 = (Graphics2D) g;

Rectangle ovalRect = new Rectangle(1, 1, 39, 39);

if (super.isOpaque())

{

g2.setColor(super.getBackground());

if (gradientColor != null && !preview)

{

setOpaque(false);

g2.setPaint(new GradientPaint(0, 0, getBackground(), getWidth(), getHeight(),

gradientColor, true));

}

g2.fillOval(ovalRect.x, ovalRect.y, ovalRect.width, ovalRect.height);

}

setBorder(null);

setOpaque(false);

Stroke old = g2.getStroke();

if (bordercolor != null)

{

g2.setColor(bordercolor);

g2.setStroke(new BasicStroke(1.7f));

g2.drawOval(ovalRect.x, ovalRect.y, ovalRect.width, ovalRect.height);

g2.drawOval(ovalRect.x + 5, ovalRect.y + 5, ovalRect.width – 10,

ovalRect.height – 10);

g2.setStroke(old);

EventDetails det = (EventDetails)((DefaultGraphCell)view.getCell()).getUserObject();

switch (det.getEvent())

{

case MessageIcon:

eventTypes.paintMessageIcon(g);

break;

case TimerIcon:

eventTypes.paintTimerIcon(g);

break;

case ErrorIcon:

eventTypes.paintErrorIcon(g);

break;

case CancelIcon:

eventTypes.paintCancelIcon(g);

break;

case CompensationIcon:

eventTypes.paintCompensationIcon(g);

break;

case RuleIcon:

eventTypes.paintRuleIcon(g);

break;

case LinkIcon:

eventTypes.paintLinkIcon(g);

break;

case TerminateIcon:

eventTypes.paintTerminateIcon(g);

break;

case MultipleIcon:

eventTypes.paintMultipleIcon(g);

break;

}

}

if (selected)

{

g2.setStroke(GraphConstants.SELECTION_STROKE);

g2.setColor(defaultBackground);

g2.setStroke(new BasicStroke(1.9f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,

10.0f, new float[] { 5f, 5f }, 0.0f));

g2.drawOval(ovalRect.x, ovalRect.y, ovalRect.width, ovalRect.height);

g2.setStroke(old);

}

super.paint(g2);

}

}

}

6. EventsType.java

public class EventsType

{

private Rectangle ovalRect = null;

private int hRadius = 18;

private int vRadius = 18;

public EventsType()

{

ovalRect = new Rectangle(0, 0, 40, 40);

}

/**

* Paint the Message Icon for the Event.

*/

public void paintMessageIcon(Graphics g)

{

if (g == null)

return;

Graphics2D g2 = (Graphics2D) g;

int x = ovalRect.x + (hRadius / 2) + 3;

int y = ovalRect.y + (vRadius / 2 + vRadius / 8) + 2;

g2.drawRect(x, y, hRadius – 1, vRadius * 3 / 4);

int xPoints[] = { x, x + hRadius – 1, x + ((hRadius – 1) / 2), x };

int yPoints[] = { y, y, y + (vRadius / 2), y };

g2.drawPolygon(xPoints, yPoints, 4);

}

/**

* Paint the Multiple Icon for the Event.

*/

public void paintMultipleIcon(Graphics g)

{

if (g == null)

return;

int side = (ovalRect.width – 8) * 4 / 10;

int x = ovalRect.x + ovalRect.width / 2;

int y = ovalRect.y + ovalRect.height / 2;

int triangle1x[] = { x – side, x, x + side };

int triangle1y[] = { y + side / 2, y – side, y + side / 2 };

int triangle2x[] = { x – side, x + side, x };

int triangle2y[] = { y – side / 2, y – side / 2, y + side };

g.fillPolygon(triangle1x, triangle1y, 3);

g.fillPolygon(triangle2x, triangle2y, 3);

}

/**

* Paint the Link Icon for the Event.

*/

public void paintLinkIcon(Graphics g)

{

if (g == null)

return;

int x = ovalRect.x + 7;

int y = ovalRect.y + 7;

int width = ovalRect.width – 12;

int height = ovalRect.height – 14;

int xPoints[] = { x, x + width * 6 / 10, x + width * 6 / 10, x + width, x + width * 6 / 10,

x + width * 6 / 10, x, x };

int yPoints[] = { y + height / 4, y + height / 4, y, y + height / 2, y + height,

y + height * 3 / 4, y + height * 3 / 4, y + height / 4 };

g.fillPolygon(xPoints, yPoints, 8);

}

/**

* Paint the Rule Icon for the Event.

*/

public void paintRuleIcon(Graphics g)

{

if (g == null)

return;

Graphics2D g2 = (Graphics2D) g;

int x = ovalRect.x + (hRadius / 2) + 4;

int y = ovalRect.y + (hRadius / 2) + 3;

g2.drawRect(x, y, hRadius – 3, vRadius – 2);

int lineWidth = hRadius – 7;

int spaceBetweenLines = (vRadius – 3) / 4;

int lineX = x + 2;

int lineY = y + spaceBetweenLines – 1;

for (int i = 0; i < 4; i++)

{

g.drawLine(lineX, lineY, lineX + lineWidth, lineY);

lineY = lineY + spaceBetweenLines;

}

}

/**

* Paint the Timer Icon for the Event.

*/

public void paintTimerIcon(Graphics g)

{

if (g == null)

return;

final float radPerSecMin = (float) (Math.PI / 30.0);

final float threePi = (float) (3.0 * Math.PI);

Graphics2D g2 = (Graphics2D) g;

g2.setColor(Color.black);

int x = ovalRect.x + 8;

int y = ovalRect.y + 8;

int width = ovalRect.width – 16;

int height = ovalRect.height – 16;

// circle

g2.drawOval(x, y, width, height);

int secondRadius = width / 2;

int minuteRadius = secondRadius * 3 / 4;

int hourRadius = secondRadius / 2;

// minute hand

float minuteAngle = threePi – (radPerSecMin * 4.0f);

drawRadius(g, x + width / 2, y + height / 2, minuteAngle, 0, minuteRadius);

// hour hand

float hourAngle = threePi – (5 * radPerSecMin * 3.0f);

drawRadius(g, x + width / 2, y + height / 2, hourAngle, 0, hourRadius);

// To indicate the hours around the circle

int ticStart;

for (int sec = 0; sec < 60; sec += 5)

{

ticStart = width * 4 / 10;

drawRadius(g, x + width / 2, y + height / 2, radPerSecMin * sec, ticStart, width / 2);

}

}

/**

* Paint the Hour indicator around the Clock for the Event.

*/

private void drawRadius(Graphics g, int x, int y, double angle, int minRadius, int maxRadius)

{

if (g == null)

return;

float sine = (float) Math.sin(angle);

float cosine = (float) Math.cos(angle);

int dxmin = (int) (minRadius * sine);

int dymin = (int) (minRadius * cosine);

int dxmax = (int) (maxRadius * sine);

int dymax = (int) (maxRadius * cosine);

g.drawLine(x + dxmin, y + dymin, x + dxmax, y + dymax);

}

/**

* Paint the Error Icon for the Event.

*/

public void paintErrorIcon(Graphics g)

{

if (g == null)

return;

int x = ovalRect.x + 10;

int y = ovalRect.y + 10;

int width = ovalRect.width – 18;

int height = ovalRect.height – 18;

int triangle1x[] = { x, x + width / 6, x + width / 3 };

int triangle1y[] = { y + height, y + height / 6, y + height / 3 };

int triangle2x[] = { x + width, x + 5 * width / 6, x + 2 * width / 3 };

int triangle2y[] = { y, y + 5 * height / 6, y + 2 * height / 3 };

int polyx[] = { x + width / 3, x + (width / 3) – (width / 10), x + 2 * width / 3,

x + (2 * width / 3) + (width / 10) };

int polyy[] = { y + height / 3, y + (height / 3) + (height / 10), y + 2 * height / 3,

y + (2 * height / 3) – (height / 10) };

g.fillPolygon(triangle1x, triangle1y, 3);

g.fillPolygon(triangle2x, triangle2y, 3);

g.fillPolygon(polyx, polyy, 4);

}

/**

* Paint the Cancel Icon for the Event.

*/

public void paintCancelIcon(Graphics g)

{

if (g == null)

return;

int x = ovalRect.x + 8;

int y = ovalRect.y + 8;

int side = ovalRect.width – 16;

int n = side * 2 / 10;

int rect1x[] = { x, x + n, x + side, x + side – n };

int rect1y[] = { y + n, y, y + side – n, y + side };

int rect2x[] = { x, x + side – n, x + side, x + n };

int rect2y[] = { y + side – n, y, y + n, y + side };

g.fillPolygon(rect1x, rect1y, 4);

g.fillPolygon(rect2x, rect2y, 4);

}

/**

* Paint the Compensation Icon for the Event.

*/

public void paintCompensationIcon(Graphics g)

{

if (g == null)

return;

int x = ovalRect.x + 8;

int y = ovalRect.y + ovalRect.height / 2;

int side = ovalRect.width / 2;

int tx1Points[] = { x, x + side / 2, x + side / 2, x };

int ty1points[] = { y, y – side / 2, y + side / 2, y };

x = x + side / 2;

int tx2Points[] = { x, x + side / 2, x + side / 2, x };

int ty2points[] = { y, y – side / 2, y + side / 2, y };

g.fillPolygon(tx1Points, ty1points, 4);

g.fillPolygon(tx2Points, ty2points, 4);

}

/**

* Paint the Terminate Icon for the Event.

*/

public void paintTerminateIcon(Graphics g)

{

if (g == null)

return;

g.fillOval(ovalRect.x + 8, ovalRect.y + 8, ovalRect.width – 16, ovalRect.height – 16);

}

}

7. EventDetails.java

public class EventDetails

{

private BPMNType cellType;

private BPMNEvent cellEvent;

private String label = “”;

private String id = “”;

public EventDetails(BPMNType type, String lab, String idE, BPMNEvent event)

{

cellEvent = event;

cellType = type;

label = lab;

id = idE;

}

public BPMNType getType()

{

return cellType;

}

public BPMNEvent getEvent()

{

return cellEvent;

}

public String getLabel()

{

return label;

}

public String getId()

{

return id;

}

}

8. BPMNType.java

public enum BPMNType

{

START,END,INTER

}

9. BPMNEvent.java

public enum BPMNEvent

{

MessageIcon, MultipleIcon, LinkIcon, RuleIcon, TimerIcon,

ErrorIcon, CancelIcon, CompensationIcon, TerminateIcon, None

}

bpmn-events

Posted in JGraph | Tagged: , , , , , , , , | 2 Comments »

Creating Web Services in Java with Apache SOAP

Posted by kalaimaan on January 29, 2009

Creating Web Services in Java with Apache SOAP

Creating web services in Java is more work than in Perl with SOAP::Lite, but the process is essentially the same. To illustrate how it’s done, let’s create the same Hello World web service and deploy it using the Apache SOAP tools.

Apache SOAP is the Apache Software Foundation’s implementation of the SOAP protocol. It is designed to run as a servlet within any Java HTTP Server. As such, it implements only the proxy part of the message handling process. Like SOAP::Lite, Apache SOAP’s list of features is impressive, sharing many of the same benefits as its Perl-based counterpart.

Installing Apache SOAP

Apache SOAP can be used as both a client and provider of SOAP web services. A server-side installation of Apache SOAP involves placing some .jar files in your classpath. You will need a separate web server that supports Servlets and Java Server Pages, such as Apache’s Tomcat (http://jakarta.apache.org/tomcat/).

The Apache SOAP homepage, http://xml.apache.org/soap/index.html, has links to both source-only and precompiled distributions of the toolkit. Installing the precompiled binary distribution is as simple as downloading a Zip archive and extracting it into a directory.

On the client, three .jar files from the distribution (soap.jar, mail.jar, and activation.jar) must be present in your classpath. Also present must be any Java API for XML Parsing (JAXP) aware XML parser, such as Xerces Version 1.4 (http://xml.apache.org/xerces-j/).

Assuming that you installed Apache SOAP .jar files in the C:\book\soap directory, set your SOAP_LIB environment variable to C:\book\soap\lib. Adding the .jar files to your classpath then entails:

set CLASSPATH = %CLASSPATH%;%SOAP_LIB%\soap.jar
set CLASSPATH = %CLASSPATH%;%SOAP_LIB%\mail.jar
set CLASSPATH = %CLASSPATH%;%SOAP_LIB%\activation.jar

Or, in the Unix Bourne shell (/bin/sh):

CLASSPATH = $CLASSPATH;$SOAP_LIB/soap.jar
CLASSPATH = $CLASSPATH;$SOAP_LIB/mail.jar
CLASSPATH = $CLASSPATH;$SOAP_LIB/activation.jar

The exact steps for a server installation will depend on which web application server you are using, but the process is essentially the same. The first step is to ensure the same three .jar files are located in your application server’s classpath.

If your application server supports the use of web application archives (WAR files), simply use the soap.war file that ships with Apache SOAP. Apache Tomcat supports this. The Apache SOAP documentation includes detailed installation instructions for Tomcat and a number of other environments.

If you intend to use the Bean Scripting Framework (BSF) to make script-based web services, you need to ensure that bsf.jar and js.jar (a BSF JavaScript implementation) are also in the web application server’s classpath.

The vast majority of problems encountered by new Apache SOAP users are related to incorrect classpaths. If you encounter problems writing web services with Apache SOAP, be sure to start your debugging by checking your classpath!

The Hello Server

We’re going to do the same things we did in Perl: create the code, deploy the service, and use the service. Example 3-12 shows the Java code for the Hello class.

Example 3-12: Hello.java

package samples;
public class Hello {
   public String sayHello(String name) {
       return "Hello " + name;
   }
}

Compile the Java class and put it somewhere in your web server’s classpath.

Deployment Descriptor

Next we must create a deployment descriptor to tell the Apache SOAP implementation everything it needs to know to dispatch sayHello messages to the samples.Hello class. This is shown in Example 3-13.

Example 3-13: Deployment descriptor for samples.Hello

<dd:service xmlns:dd="http://xml.apache.org/xml-soap/deployment" 
    id="urn:Example1">
 <dd:provider type="java"
              scope="Application"
              methods="sayHello">
    <dd:java class="samples.Hello"
             static="false" />
 </dd:provider>  
 <dd:faultListener>
  org.apache.soap.server.DOMFaultListener
 </dd:faultListener>
 <dd:mappings />
</dd:service>

The information contained within a deployment descriptor is fairly basic. There is the class name of the Java code being invoked (<dd:java class="samples.Hello" static="false" />), and an indication of the session scope of the service class (application or session scope, as defined by the Java Servlet specification), an indication of which faultListener to use (used to declare how faults are handled by the SOAP engine), and a listing of Java-to-XML type mappings. We will demonstrate later how the type mappings are defined.

Apache SOAP supports the use of pluggable providers that allow web services to be implemented not only as Java classes, but as Enterprise Java Beans, COM Classes, and Bean Scripting Framework scripts. Full information about how to use pluggable providers is available in the documentation and not covered here.

While simple in structure, deployment descriptor files must be created for every web service that you want to deploy. Thankfully, there are tools available that automate that process, but they still require the developer to walk through some type of wizard to select the Java class, the methods, and the type mappings. (A type mapping is an explicit link between a type of XML data and a Java class, and the Java classes that are used to serialize or deserialize between those types.)

Once the file is created, you have to deploy it with the Apache SOAP service manager. There are two ways to do this: you can use the Service Manager Client or, if you’re using the XML-based Service Manager that ships with Apache SOAP, modify the deployment registry directly.

The first method requires executing the following command:

% java org.apache.soap.server.ServiceManagerClient http://hostname:port/soap/servlet/rpcrouter deploy foo.xml

Where hostname:port is the hostname and port that your web service is listening on.

One interesting fact you should notice here is that the Apache Service Manager is itself a web service, and that deployment of a new service takes place by sending a SOAP message to the server that includes the deployment descriptor. While this is handy, it’s not necessarily all that secure (considering the fact that it would allow anybody to deploy and undeploy services on your web server). To disable this, set the SOAPInterfaceEnabled option in the soap.xml configuration file to false. This will prevent the ServiceManagerClient from working.

The second approach will only work if you’re using the XML Configuration Manager. This component allows you to store deployment information in an XML file. This file is located in the web-apps folder where your Apache SOAP servlet is located.

The XML is nothing more than a root element that contains all of the deployment descriptors for all of the services deployed. To deploy the Hello World service, simply take the deployment descriptor we wrote earlier and append it to this list. The next time that the SOAP servlet is started, the service manager will be reinitialized and the new service will be ready for use. A sample configuration file is given in Example 3-14.

Example 3-14: Apache SOAP configuration file

<root>
  <dd:service xmlns:dd="http://xml.apache.org/xml-soap/deployment"
              id="urn:Example1">
    <dd:provider type="java"
                 scope="Application"
                 methods="sayHello">
       <dd:java class="samples.Hello" 
                static="false" />
    </dd:provider>
    <dd:faultListener>
     org.apache.soap.server.DOMFaultListener
    </dd:faultListener>
    <dd:mappings />
   </dd:service>
</root>

The Hello Client

To invoke the Hello World service, use the Java class in Example 3-15.

Example 3-15: Hello client in Java

import java.io.*;
import java.net.*;
import java.util.*;
import org.apache.soap.*;
import org.apache.soap.rpc.*;

public class Example1_client {

  public static void main (String[] args) 
       throws Exception {

    System.out.println("\n\nCalling the SOAP Server to say hello\n\n");       
    URL url = new URL (args[0]);
    String name = args[1];

    Call call = new Call (  );
    call.setTargetObjectURI("urn:Example1");
    call.setMethodName("sayHello");
    call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC;);
    Vector params = new Vector (  );
    params.addElement (new Parameter("name", String.class, name, null));
    call.setParams (params);

    System.out.print("The SOAP Server says: ");

    Response resp = call.invoke(url, "");

    if (resp.generatedFault (  )) {
      Fault fault = resp.getFault (  );
      System.out.println ("\nOuch, the call failed: ");
      System.out.println ("  Fault Code   = " + fault.getFaultCode (  ));
      System.out.println ("  Fault String = " + fault.getFaultString (  ));
    } else {
      Parameter result = resp.getReturnValue (  );
      System.out.print(result.getValue (  ));
      System.out.println(  );
    }
  }
}

The amount of code to accomplish this relatively simple operation may seem surprising (nine lines to actually initialize and invoke the web services call). Java will never be as terse as Perl and other scripting languages, but it has other strengths. Also, various Java-based SOAP toolkits such as The Mind Electric’s GLUE and IBM’s Web Services ToolKit support dynamic proxy interfaces that cut down the amount of code necessary to invoke web services. Those interfaces, however, generally require additional mechanisms, such as WSDL, to simplify the programming interface. We will take a look at these dynamic proxies later in Chapter 5. For now, if you compile and run this class, you’ll end up with the same result that we saw in the Perl example:

% java samples.Hello http://localhost/soap/servlet/rpcrouter James

Calling the SOAP Server to say hello
The SOAP Server says: Hello James

%

Your Java web service is finished. If you have both the Perl and Java versions installed, run the Perl client script again but point it at the Java version of the Hello World service (the modified script is shown in Example 3-16). You’ll see that everything still works.

Posted in Soap Service | Tagged: , , , | 1 Comment »

Group selection, tofront, toback

Posted by kalaimaan on January 29, 2009

  • Select all child in a group

Here groupCell is mean by parent DefaultgraphCell

jGraph.addSelectionCells(groupCell.getChildren().toArray());

  • Send back the selected cells

jGraph.getGraphLayoutCache().toFront(jGraph.getSelectionCells.toArray());

  • Bring the selected cells into back

jGraph.getGraphLayoutCache().toBack(jGraph.getSelectionCells.toArray());

Posted in JGraph | Tagged: , , | Leave a Comment »

KeyPress Event for JGraph Objects

Posted by kalaimaan on January 29, 2009

Write our own class extends KeyAdapter

Files Details:

  • GraphKeyListener.java

/**
*
* @author kalaimaan
*
* keypress event for graph objects
*
*/
public class GraphKeyListener extends KeyAdapter
{

JGraph jGraph = null;

DefaultGraphModel jGraphModel = null;

public GraphKeyListener(JGraph jGraph , DefaultGraphModel jGraphModel)
{
this.jGraph = jGraph;
this.jGraphModel = jGraphModel;
}

public void keyPressed(KeyEvent event)
{
int keyCode = event.getKeyCode();

// Changes for ViewletDesigner : stop operation in the edit mode
if (jGraph.isEditing())
return;

switch (keyCode)
{
case KeyEvent.VK_UP:
case KeyEvent.VK_DOWN:
case KeyEvent.VK_RIGHT:
case KeyEvent.VK_LEFT:
translateSelectedCells(keyCode);
break;
}
}

public boolean isTranslationEvent(int keyCode)
{
boolean isTranslation = false;

return isTranslation;
}

public void translateSelectedCells(int keyCode)
{
Object[] cells = jGraph.getSelectionModel().getSelectionCells();

double dx = 0;
double dy = 0;
double gridSize = jGraph.getGridSize();
switch (keyCode)
{
case KeyEvent.VK_UP:
dx = 0;
dy = -gridSize;
break;
case KeyEvent.VK_DOWN:
dx = 0;
dy = gridSize;
break;
case KeyEvent.VK_LEFT:
dx = -gridSize;
dy = 0;
break;
case KeyEvent.VK_RIGHT:
dx = gridSize;
dy = 0;
break;
}

for (Object cell : cells)
{
AttributeMap map = ((DefaultGraphCell) cell).getAttributes();
if (GraphConstants.getBounds(map) != null)
{
Rectangle cellBounds = GraphConstants.getBounds(map).getBounds();

cellBounds.x = (cellBounds.x += dx) < 0 ? 0 : (cellBounds.x);
cellBounds.y = (cellBounds.y += dy) < 0 ? 0 : (cellBounds.y);

GraphConstants.setBounds(map, cellBounds);
}
}

jGraphModel.cellsChanged(cells);
}
}

Add listener to JGraph object

  • jGraph.addKeyListener(new GraphKeyListener(jGraph, jGraphModel));

Sample Picture :

keypress-picture

Posted in JGraph | Tagged: , | 1 Comment »

Add components in JGraph like JText, JTextArea, JComboBox

Posted by kalaimaan on January 29, 2009

I had a new experience with JGraph, I like to say how to add  jComponent objects in JGraph.

Here is the sample, just have it and feel good.

Adding JComponent in Jgraph, before start coping read below to understand the concept how to add a component in jgraph?

Through vertex class we could able to add JComponent in jgraph. The vertex have the render method (getRendererComponent() ) to add a component as object.

The vertex class is executed by DefaultCellViewFactory. ( check the inner class of JComponentCellViewFactory in AddCompSample class)

The DefaultCellViewFactory is add in JGragh as a factory method (check the class JComponentView) to know how we differentiate the componets.

Sample code :

We need Four files, check the code and create the same .

Class name Details:

  • AddCompSample.java
  • JcomponentType.java
  • JComponentCell.java
  • JComponentView.java

File 1:  AddCompSample.java

/**
*
* @author Kalaimaan
*
*         Adding different component in Jgraph using vertex
*
*/
public class AddCompSample extends JFrame implements ActionListener
{
protected JGraph jGraph = null;
protected DefaultGraphModel jGraphModel = null;

private JButton btnInsert = null;
private JButton btnDelete = null;
private JComboBox cbxElements = null;
private JComboBox cbxObject = null;

private static int cNum = 0;

private static int gNum = 0;

private HashMap<String, DefaultGraphCell> allCellList = new HashMap<String, DefaultGraphCell>();

public AddCompSample()
{
super(“JGraph Demo-kalaimaan”);
initGraph();
}

/**
*
*/
private void initGraph()
{
jGraphModel = new DefaultGraphModel();
jGraph = new JGraph(jGraphModel);

jGraph.setGridColor(Color.lightGray);
jGraph.setGridMode(JGraph.LINE_GRID_MODE);
jGraph.setGridSize(20);
jGraph.setGridEnabled(true);
jGraph.setGridVisible(true);
jGraph.setHandleColor(Color.red);
jGraph.setSelectionEnabled(true);

setLayout(new BorderLayout());

addGraphLayout();
setSize(600, 600);
setVisible(true);
}

/**
*
*/
private void addGraphLayout()
{
jGraphModel.addGraphModelListener(new GraphMode());
jGraph.getGraphLayoutCache().setFactory(new JComponentCellViewFactory());
add(toolButton(), BorderLayout.NORTH);
add(jGraph, BorderLayout.CENTER);
}

/**
*
* @return
*/
private JPanel toolButton()
{
JPanel temp = new JPanel();

// cbxElements = new JComboBox();
// cbxElements.setPreferredSize(new Dimension(100, 25));
// cbxElements.addActionListener(this);
// temp.add(cbxElements);

cbxObject = new JComboBox();
cbxObject.addItem(“Text”);
cbxObject.addItem(“TextArea”);
cbxObject.addItem(“ComboBox”);
cbxObject.addItem(“CheckBox”);
cbxObject.addItem(“Button”);
cbxObject.addItem(“Lable”);
cbxObject.setPreferredSize(new Dimension(100, 25));
cbxObject.addActionListener(this);
temp.add(cbxObject);

btnInsert = new JButton(“Insert”);
btnInsert.setPreferredSize(new Dimension(100, 25));
btnInsert.addActionListener(this);
temp.add(btnInsert);

btnDelete = new JButton(“Delete”);
btnDelete.setPreferredSize(new Dimension(100, 25));
btnDelete.addActionListener(this);
temp.add(btnDelete);

return temp;
}

public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e)
{
e.printStackTrace();
}
AddCompSample gug = new AddCompSample();
gug.setDefaultCloseOperation(EXIT_ON_CLOSE);
}

@Override
public void actionPerformed(ActionEvent e)
{
String action = e.getActionCommand();

if (action.equalsIgnoreCase(“Insert”))
insertElement();
else if (action.equalsIgnoreCase(“Delete”))
deleteElement();
}

/**
*
*/
private void insertElement()
{
String name = cbxObject.getSelectedItem().toString();
String cellId = cellNumber();
JComponentCell jc = null;
if (name.equalsIgnoreCase(“Text”))
jc = new JComponentCell(JcomponentType.TEXT, “Text -” + cellId);
else if (name.equalsIgnoreCase(“TextArea”))
jc = new JComponentCell(JcomponentType.AREA, “TextArea -” + cellId);
else if (name.equalsIgnoreCase(“ComboBox”))
jc = new JComponentCell(JcomponentType.COMBO, “ComboBox -” + cellId);
else if (name.equalsIgnoreCase(“CheckBox”))
jc = new JComponentCell(JcomponentType.CHECK, “CheckBox -” + cellId);
else if (name.equalsIgnoreCase(“Button”))
jc = new JComponentCell(JcomponentType.BUTTON, “Button -” + cellId);
else if (name.equalsIgnoreCase(“Lable”))
jc = new JComponentCell(JcomponentType.LABEL, “Label -” + cellId);

DefaultGraphCell cell = getCell(jc);
jGraph.getGraphLayoutCache().insert(cell);
allCellList.put(cellId, cell);
}

/**
*
* @param jCell
* @return
*/
private DefaultGraphCell getCell(JComponentCell jCell)
{
DefaultGraphCell cell = new DefaultGraphCell(jCell);

AttributeMap map = new AttributeMap();
Rectangle rec = null;
switch (jCell.getType())
{
case AREA:
rec = new Rectangle(20, 20, 150, 50);
break;
case BUTTON:
rec = new Rectangle(20, 20, 150, 30);
break;

case TEXT:
case CHECK:
case COMBO:
case LABEL:
default:
rec = new Rectangle(20, 20, 150, 25);
}

GraphConstants.setBounds(map, rec);
GraphConstants.setGradientColor(map, Color.white.brighter());
GraphConstants.setBorderColor(map, Color.blue);
GraphConstants.setBackground(map, Color.gray);
GraphConstants.setSizeableAxis(map, 3);
GraphConstants.setOpaque(map, true);
GraphConstants.setEditable(map, false);
cell.setAttributes(map);

return cell;
}

/**
*
*/
private void deleteElement()
{
Object[] object = jGraph.getSelectionCells();
for (Object obj : object)
{
if (obj == null)
continue;

String key = ((DefaultGraphCell) obj).getUserObject().toString();
allCellList.remove(key);
jGraph.getGraphLayoutCache().remove(new Object[] { obj });
}
}

private String cellNumber()
{
return “” + cNum++;
}

private String groupNumber()
{
return “Group-” + gNum++;
}

private class GraphMode implements GraphModelListener
{
@Override
public void graphChanged(GraphModelEvent e)
{
jGraph.clearOffscreen();
}
}

private class JComponentCellViewFactory extends DefaultCellViewFactory
{
protected VertexView createVertexView(Object objCell)
{
DefaultGraphCell cell = (DefaultGraphCell) objCell;
VertexView vertex = null;
vertex = new JComponentView(cell);

return vertex;
}
}

}

File 2: JcomponentType.java

public enum JcomponentType
{
LABEL, TEXT, CHECK, COMBO, AREA , BUTTON;
}

File 3: JComponentCell.java

public class JComponentCell
{
private JcomponentType cellType;
private String label = “”;

public JComponentCell(JcomponentType type, String label)
{
this.label = label;
this.cellType = type;
}

public JcomponentType getType()
{
return cellType;
}

public String getLabel()
{
return label;
}

public void setLabel(String label)
{
this.label = label;
}
}

File 4: JComponentView.java

public class JComponentView extends VertexView
{
private static CompViewRenderer renderer = new CompViewRenderer();

private static class CompViewRenderer extends VertexRenderer
{
public CompViewRenderer()
{
super();
}

@Override
public Component getRendererComponent(JGraph jGraph, CellView cellView, boolean selected, boolean focused,
boolean preview)
{
Component comp = null;
DefaultGraphCell cell = (DefaultGraphCell) cellView.getCell();
JComponentCell jcell = (JComponentCell)cell.getUserObject();
switch (jcell.getType())
{
case LABEL:
JLabel lbl = (JLabel) super.getRendererComponent(jGraph, cellView, selected, focused, preview);
lbl.setText(jcell.getLabel());
comp = lbl;
break;
case TEXT:
comp = new JTextField(jcell.getLabel());
break;
case COMBO:
comp = new JComboBox();
break;
case CHECK:
comp = new JCheckBox();
break;
case AREA:
JTextArea txtArea = new JTextArea();
comp = new JScrollPane(txtArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
comp.setBounds(((Rectangle2D) cell.getAttributes().get(GraphConstants.BOUNDS)).getBounds());
break;
case BUTTON:
comp = new JButton(jcell.getLabel());
break;
}
return comp;
}
}

public JComponentView(Object cell)
{
super(cell);
}

@Override
public CellViewRenderer getRenderer()
{
return renderer;
}
}

Sample Screen Shot :

addcomp-picture

Posted in Java, JGraph | Tagged: , , , , , , , , , , , | 18 Comments »

Group and UNGroup the selected element

Posted by kalaimaan on January 28, 2009

Hi Friends,

This is the first post in this blog and i like to share my technical information with you all

The post is related to JGraph and How are could insert, delete , group and ungroup the element in JGraph

We can use the jgraph for mutipurpose. here i am sharing the small bit

Example 1:

public class GUGSample extends JFrame implements ActionListener
{
protected JGraph jGraph = null;
protected DefaultGraphModel jGraphModel = null;

private JButton btnInsert = null;
private JButton btnDelete = null;
private JButton btnGroup = null;
private JButton btnUnGroup = null;

private static int cNum = 0;

private static int gNum = 0;

private HashMap<String, DefaultGraphCell> allCellList = new HashMap<String, DefaultGraphCell>();

private HashMap<String, DefaultGraphCell> groupList = new HashMap<String, DefaultGraphCell>();

public GUGSample()
{
super(“JGraph Demo-kalaimaan”);
initGraph();
}

/**
*
*/
private void initGraph()
{
jGraphModel = new DefaultGraphModel();
jGraph = new JGraph(jGraphModel);

jGraph.setGridColor(Color.lightGray);
jGraph.setGridMode(JGraph.LINE_GRID_MODE);
jGraph.setGridSize(20);
jGraph.setGridEnabled(true);
jGraph.setGridVisible(true);
jGraph.setHandleColor(Color.red);
jGraph.setSelectionEnabled(true);

setLayout(new BorderLayout());

addGraphLayout();
setSize(600, 600);
setVisible(true);
}

/**
*
*/
private void addGraphLayout()
{
jGraphModel.addGraphModelListener(new GraphMode());
add(toolButton(), BorderLayout.NORTH);
add(jGraph, BorderLayout.CENTER);

}

/**
*
* @return
*/
private JPanel toolButton()
{
JPanel temp = new JPanel();
btnInsert = new JButton(“Insert”);
btnInsert.setPreferredSize(new Dimension(100, 25));
btnInsert.addActionListener(this);
temp.add(btnInsert);

btnDelete = new JButton(“Delete”);
btnDelete.setPreferredSize(new Dimension(100, 25));
btnDelete.addActionListener(this);
temp.add(btnDelete);

btnGroup = new JButton(“Group”);
btnGroup.setPreferredSize(new Dimension(100, 25));
btnGroup.addActionListener(this);
temp.add(btnGroup);

btnUnGroup = new JButton(“UnGroup”);
btnUnGroup.setPreferredSize(new Dimension(100, 25));
btnUnGroup.addActionListener(this);
temp.add(btnUnGroup);

return temp;
}

public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e)
{
e.printStackTrace();
}
GUGSample gug = new GUGSample();
gug.setDefaultCloseOperation(EXIT_ON_CLOSE);
}

@Override
public void actionPerformed(ActionEvent e)
{
String action = e.getActionCommand();

if (action.equalsIgnoreCase(“Insert”))
insertElement();
else if (action.equalsIgnoreCase(“Delete”))
deleteElement();
else if (action.equalsIgnoreCase(“Group”))
groupElements();
else if (action.equalsIgnoreCase(“UnGroup”))
unGroupElements();
}

/**
*
*/
private void insertElement()
{
String cn = cellNumber();
DefaultGraphCell cell = new DefaultGraphCell(cn);

AttributeMap map = new AttributeMap();
Rectangle rec = new Rectangle(20, 20 , 100,50);
GraphConstants.setBounds(map, rec);
GraphConstants.setGradientColor(map, Color.yellow.brighter());
GraphConstants.setBorderColor(map, Color.blue);
GraphConstants.setBackground(map, Color.white);
GraphConstants.setSizeableAxis(map, 3);
GraphConstants.setOpaque(map, true);
GraphConstants.setEditable(map, false);
cell.setAttributes(map);

jGraph.getGraphLayoutCache().insert(cell);
allCellList.put(cn, cell);
}

/**
*
*/
private void deleteElement()
{
Object[] object = jGraph.getSelectionCells();
for(Object obj : object)
{
if(obj==null)
continue;

String key =  ((DefaultGraphCell)obj).getUserObject().toString();
allCellList.remove(key);
groupList.remove(key);
jGraph.getGraphLayoutCache().remove(new Object[] {obj});
}

}

private void groupElements()
{
Object[] object = jGraph.getSelectionCells();
String gn = groupNumber();

DefaultGraphCell groupCell = new DefaultGraphCell(gn);
AttributeMap map = new AttributeMap();
Rectangle rec = new Rectangle(20, 20 , 100,50);
GraphConstants.setBounds(map, rec);
GraphConstants.setGradientColor(map, Color.white.darker());
GraphConstants.setGroupOpaque(map, true);
GraphConstants.setBorderColor(map, Color.GREEN.darker());
GraphConstants.setDashOffset(map, 2);
GraphConstants.setBackground(map, Color.white);
GraphConstants.setSizeableAxis(map, 3);
GraphConstants.setOpaque(map, true);
GraphConstants.setEditable(map, false);
groupCell.setAttributes(map);

jGraph.getGraphLayoutCache().insertGroup(groupCell, object);
groupList.put(gn, groupCell);

jGraph.clearOffscreen();
}

private void unGroupElements()
{
Object[] object = jGraph.getSelectionCells();
for(Object obj : object)
{
DefaultGraphCell cell = (DefaultGraphCell) obj;
if(cell!=null && cell.getParent()!=null)
{
DefaultGraphCell groupCell = (DefaultGraphCell)cell.getParent();
int childCount =  groupCell.getChildCount();
groupCell.remove(cell);
jGraph.getGraphLayoutCache().ungroup(new Object[]{cell});
jGraph.getGraphLayoutCache().insert(cell);

if(childCount==2)
{
groupList.remove(groupCell.getUserObject().toString());
jGraph.getGraphLayoutCache().remove(new Object[] {cell});
}
}
}

jGraph.clearOffscreen();
}

private String cellNumber()
{
return “Cell-” + cNum++;
}

private String groupNumber()
{
return “Group-” + gNum++;
}

private class GraphMode implements GraphModelListener
{
@Override
public void graphChanged(GraphModelEvent e)
{
jGraph.clearOffscreen();
}
}
}

Sample screen shot

gug-picture1

Posted in JGraph | Tagged: , , , , | Leave a Comment »