Working with the graph widget
From Protege Wiki
Revision as of 17:31, August 14, 2007 by JenniferVendetti (talk | contribs)
Programmatic Access to the Graph Widget
Two questions about programmatic access to the graph widget have been posted on the protege-discussion mailing list with some regularity:
- How do I programmatically save the contents of the graph widget to an image?
- How do I programmatically get position information for nodes in the graph widget?
The following code snippet shows how to accomplish both. It uses the newspaper example project that comes with the default installation of Protege. In the newspaper example project, The "employees" slot attached to the "Organization" class is configured to use the graph widget.
public class GraphWidget_Test { private static final String projectFileName = "C:/Protege_3.3/examples/newspaper/newspaper.pprj"; public static void main(String[] args) { // open the newspaper example Collection errors = new ArrayList(); Project project = new Project(projectFileName, errors); // get the instance and slot objects from the kb that we want to work with Instance instance = project.getKnowledgeBase().getInstance("instance_00064"); // a.k.a. -> "San Jose Mercury News" Slot slot = project.getKnowledgeBase().getSlot("employees"); // necessary to put the clswidget into a jframe because the graph // widget uses a 3rd party drawing library that won't initiliaze // until it detects that it's in a window ClsWidget cw = project.createRuntimeClsWidget(instance); JFrame frame = new JFrame(); frame.getContentPane().add((Component) cw); frame.pack(); // get the slot widget for the "employees" slot SlotWidget sw = cw.getSlotWidget(slot); if (sw instanceof GraphWidget) { GraphWidget gw = (GraphWidget) sw; BufferedImage image = gw.getImage(); try { // save contents of graph widget as jpg File f = new File("c:\\temp\\graph-widget.jpg"); ImageIO.write(image, "jpg", f); // save contents of graph widget as png File f2 = new File("c:\\temp\\graph-widget.png"); ImageIO.write(image, "png", f2); } catch(java.io.IOException e) { System.out.println(e.getMessage()); } // print the position information for all of the slot values // of the employee slot ArrayList ownSlotValues = new ArrayList(instance.getDirectOwnSlotValues(slot)); Iterator i = ownSlotValues.iterator(); while (i.hasNext()) { Instance ownSlotValue = (Instance) i.next(); Object obj = gw.getPositionInfo(instance, slot, ownSlotValue); System.out.println("Position information for " + ownSlotValue.getBrowserText() + ": " + obj); } } } }