Kalaimaan

Doing simple things to make great life

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

18 Responses to “Add components in JGraph like JText, JTextArea, JComboBox”

  1. RedCross said

    Thank You!!!! I searched a whole day for an example with “no-String” vertices. Now I found one :).

  2. selmak said

    Thank you for this example, it really helped me in my application.
    I have a question. I want to define an actionPerformed for the jButton, when I add it, it doesn’t work. Do you know how to do this?
    Thakn you for your help.

  3. kalaimaan said

    Hi,

    You are welcome, check the addition code to be implemented

    Add the below code to execute when ever the default graphcell action by mouse like click, press etc

    private class JComponentGraphMouselListener extends MouseAdapter
    {
    @Override
    public void mouseClicked(MouseEvent arg0)
    {
    // TODO Auto-generated method stub
    super.mouseClicked(arg0);
    JOptionPane.showMessageDialog(null, “test mouse click”);
    }

    @Override
    public void mousePressed(MouseEvent e)
    {
    // TODO Auto-generated method stub
    super.mousePressed(e);
    JOptionPane.showMessageDialog(null, “test Mousepress”);
    }

    @Override
    public void mouseReleased(MouseEvent e)
    {
    // TODO Auto-generated method stub
    super.mouseReleased(e);
    JOptionPane.showMessageDialog(null, “test Mouse release”);
    }
    }

    <<>>

    jGraph.addMouseListener(new JComponentGraphMouselListener());

  4. selmak said

    Hi,
    Thank you for your answer.
    Yes, this code works, but how can I do the same thing only if a cell is clicked for example. I explain: with this code, I have the message “test mouse click” where ever I click in the graph. I want to do the same thing only if the mouse is clicked on the cells.
    Thanks in advance.

  5. selmak said

    here is the answer to my last question:

    public class JComponentGraphMouselListener extends MouseAdapter
    {
    JGraph graph;
    public JComponentGraphMouselListener(JGraph jgraph){
    graph = jgraph;
    }

    public void mouseClicked(MouseEvent arg0)
    {
    // TODO Auto-generated method stub
    super.mouseClicked(arg0);
    int i = 0;

    Object[] t = graph.getSelectionCells();
    DefaultGraphCell comp;

    if (t.length>0) {
    comp = (DefaultGraphCell) t[t.length – 1];
    if (comp.getClass().toString().equals(“class org.jgraph.graph.DefaultGraphCell”))
    JOptionPane.showMessageDialog(null, “test mouse click”);
    }
    }
    }

    <>

    jGraph.addMouseListener(new JComponentGraphMouselListener(jGraph));

  6. Biguá said

    Dude… I love you =)

  7. feriel said

    Salut

    J’ai essayé de faire tourner votre code pour s’en inspirer à construire mes cellules mais ça ne marche pas. Je ne sais pas pourquoi.

    Pouvez-vous m’aider?

    • kalaimaan said

      you r welcome.. If possible try to communicate in English other no probs….
      Give some time i will check .. after long back i started again to post new and reply .. will answer u soon

  8. vinay said

    hi thanks for above code,
    I have added components in Jgraph area, can you tell me how can i connect two compponents using an arrow?…
    Thnaks in advance.

    • kalaimaan said

      you r welcome
      Give some time i will check .. after long back i started again to post new and reply .. will answer u soon

      • johan said

        this is something i wonder about too.
        thanks for the code btw, you rock!

      • johan said

        i have to modfy my question, i found out that i have to add a port manually, but the edges only originates from the center of the cell, not from the bounds. do you have any idea how to fix this?

        thanks in advance! //johan

  9. Adan Rodriguez said

    hi, this blog is great! Congratulations.
    I want to insert jcomponents into vertex, using JGraphX. But JGraph and JGraphX API’s are very diferents. Can you help me?

    • kalaimaan said

      you r welcome
      Pls give some time i will check .. after long back i started again to post new and reply .. will answer u soon

  10. jp said

    Cool stuff. The problem is, the components aren’t themselves interactive. If I drop a combobox on the screen and click on the combobox, I can’t actually go through the combobox choices…

  11. marinus said

    Hi

    your post seems very helpful. but how can I add a polygon (hexagon or pentagon) as a vertex? thanks.

  12. KHADRAOUI said

    Hi,
    i created my tool that allow users to create class diagram, but i want to add fields into a cell, when user do a right clic on cell, a menu be appear and user can add, remove or update fields, i need help please, i try many examples but dosn’t work 😦 . the right clic, menu works , i need just to know how create textFeald into a cell.

Leave a comment