Kalaimaan

Doing simple things to make great life

Posts Tagged ‘KeyPress’

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 »