Kalaimaan

Doing simple things to make great life

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

Advertisements

One Response to “KeyPress Event for JGraph Objects”

  1. zsolt said

    I needed exactly this code. You spared me 2 hours of api search, and 5 minutes of coding. 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: