Example #1
0
 void refreshGraphIfNeeded() {
   if (cell != null) {
     String label = graphComponent.getGraph().getLabel(cell);
     int istart = label.indexOf("<i>s=") + 5;
     String labelNoStart = label.substring(istart);
     String oldStart = label.substring(istart, istart + labelNoStart.indexOf("</i>"));
     String newStart = jtflStart.getText();
     if (!oldStart.equalsIgnoreCase(newStart)) {
       String newLabel = getNewLabel(AngleItem.START, newStart);
       graphComponent.getGraph().cellLabelChanged(cell, newLabel, false);
     }
     int iEnd = label.indexOf("<i>e=") + 5;
     String labelNoEnd = label.substring(iEnd);
     String oldEnd = label.substring(iEnd, iEnd + labelNoEnd.indexOf("</i>"));
     String newEnd = jtflEnd.getText();
     if (!oldEnd.equalsIgnoreCase(newEnd)) {
       String newLabel = getNewLabel(AngleItem.END, newEnd);
       graphComponent.getGraph().cellLabelChanged(cell, newLabel, false);
     }
     int iInc = label.indexOf("<i>s=") + 5;
     String labelNoInc = label.substring(iInc);
     String oldInc = label.substring(iInc, iInc + labelNoInc.indexOf("</i>"));
     String newInc = jtflInc.getText();
     if (!oldInc.equalsIgnoreCase(newInc)) {
       String newLabel = getNewLabel(AngleItem.INC, newInc);
       graphComponent.getGraph().cellLabelChanged(cell, newLabel, false);
     }
   }
 }
Example #2
0
 /** Test of draw method, of class EventsTreeAdapter. */
 @Test
 public void testDraw() {
   int width = 500, height = 500;
   //        Map<String, Object> edge2 = new HashMap<String, Object> ();
   //        edge2.put(mxConstants.STYLE_EXIT_X, "0.5");
   //        edge2.put(mxConstants.STYLE_EXIT_Y, "1");
   System.out.println("draw");
   mxGraphComponent mxGraphComponent1 = new mxGraphComponent(new mxGraph());
   mxGraphComponent1.setBounds(0, 0, width, height);
   expect(drawPanel.getComponents()).andReturn(new Component[] {mxGraphComponent1}).anyTimes();
   replay(drawPanel);
   //        expect(tree.getEvents()).andReturn(new HashMap<Integer, Event>()).anyTimes();
   //        expect(tree.getEdges()).andReturn(new HashMap<Integer, Edge>()).anyTimes();
   //        replay(tree);
   instance.draw(drawPanel);
   eventTreeUtil = new EventTreeUtil(drawPanel);
   assertNotNull(eventTreeUtil.getCellByID("" + 2));
   assertNotNull(eventTreeUtil.getCellByID("E" + 0));
   assertTrue(eventTreeUtil.getCellByID("" + 2).getGeometry().getWidth() == (double) (width / 2));
   //        mxCellState targetState =
   // mxGraphComponent1.getGraph().getView().getState(eventTreeUtil.getCellByID("final"));
   //        mxCellState edgeState =
   // mxGraphComponent1.getGraph().getView().getState(eventTreeUtil.getCellByID("E"+0));
   //        edgeState.setStyle(edge2);
   //        mxConnectionConstraint connectionConstraint =
   // mxGraphComponent1.getGraph().getConnectionConstraint(edgeState, targetState, false);
   //        assertTrue(connectionConstraint.getPoint().equals(new mxPoint(0.5, 0.5)));
   instance.draw(drawPanel);
   assertNotNull(eventTreeUtil.getCellByID("" + 3));
   assertNotNull(eventTreeUtil.getCellByID("E" + 1));
   assertNotNull(eventTreeUtil.getCellByID("E" + 2));
   assertTrue(eventTreeUtil.getCellByID("" + 2).getGeometry().getWidth() == (double) (width / 3));
 }
Example #3
0
  /** Saves XML+PNG format. */
  protected void saveXmlPng(TrackSchemeFrame frame, String filename, Color bg) throws IOException {
    final mxGraphComponent graphComponent = trackScheme.getGUI().graphComponent;
    final mxGraph graph = trackScheme.getGraph();

    // Creates the image for the PNG file
    BufferedImage image =
        mxCellRenderer.createBufferedImage(
            graph, null, 1, bg, graphComponent.isAntiAlias(), null, graphComponent.getCanvas());

    // Creates the URL-encoded XML data
    mxCodec codec = new mxCodec();
    String xml = URLEncoder.encode(mxXmlUtils.getXml(codec.encode(graph.getModel())), "UTF-8");
    mxPngEncodeParam param = mxPngEncodeParam.getDefaultEncodeParam(image);
    param.setCompressedText(new String[] {"mxGraphModel", xml});

    // Saves as a PNG file
    FileOutputStream outputStream = new FileOutputStream(new File(filename));
    try {
      mxPngImageEncoder encoder = new mxPngImageEncoder(outputStream, param);

      if (image != null) {
        encoder.encode(image);
      } else {
        JOptionPane.showMessageDialog(graphComponent, "No Image Data");
      }
    } finally {
      outputStream.close();
    }
  }
Example #4
0
 /** Test of removeEdge method, of class EventsTreeAdapter. */
 @Test(expected = NullPointerException.class)
 public void testRemoveEdge() {
   int width = 500, height = 500;
   System.out.println("removeEdge");
   mxGraphComponent mxGraphComponent1 = new mxGraphComponent(new mxGraph());
   mxGraphComponent1.setBounds(0, 0, width, height);
   expect(drawPanel.getComponents()).andReturn(new Component[] {mxGraphComponent1}).anyTimes();
   replay(drawPanel);
   instance.draw(drawPanel);
   instance.draw(drawPanel);
   instance.draw(drawPanel);
   eventTreeUtil = new EventTreeUtil(drawPanel);
   instance.removeEdge(eventTreeUtil.getCellByID("E" + 2));
   try {
     assertNull(eventTreeUtil.getCellByID("E" + 2));
     fail("Nie usunieto 2.");
   } catch (NullPointerException exception) {
     try {
       assertNull(eventTreeUtil.getCellByID("E" + 5));
       fail("Nie usunieto 5.");
     } catch (NullPointerException ex) {
       assertNull(eventTreeUtil.getCellByID("E" + 6));
     }
   }
 }
Example #5
0
  // Create a new document
  public void clear() {
    areaEditPanel.clear();
    puzzleEditPanel.clear();

    areaGraph = new mxGraph();
    areaGraph.setAutoSizeCells(true);
    areaGraphComponent.setGraph(areaGraph);
    areaGraphLayout =
        new mxOrganicLayout(
            areaGraph,
            new Rectangle(0, 0, graphPanel.getBounds().width, graphPanel.getBounds().height));
    areaGraph.setEnabled(false);

    puzzleGraph = new mxGraph();
    puzzleGraph.setAutoSizeCells(true);
    puzzleGraphComponent.setGraph(puzzleGraph);
    puzzleGraphOrganicLayout =
        new mxOrganicLayout(
            puzzleGraph,
            new Rectangle(0, 0, graphPanel.getBounds().width, graphPanel.getBounds().height));
    puzzleGraphHierLayout = new mxHierarchicalLayout(puzzleGraph, SwingConstants.WEST);
    hierarchyRoot = null;

    AreaEditPanel.reset();
    CombinePuzzleBlock.reset();
    InsertionPuzzleBlock.reset();
    DoorUnlockBlock.reset();
    FilterBlock.reset();
    InsertionPuzzleBlock.reset();
    ItemRequestPuzzleBlock.reset();
    PropertyChangePuzzleBlock.reset();
    SpawnPuzzleBlock.reset();
    OutputBlock.reset();
    ORBlock.reset();
  }
Example #6
0
  public mxGraphComponent gerar() {
    graph.getModel().beginUpdate();

    if (!gerado) {
      Object fim =
          graph.insertVertex(
              parent,
              null,
              "Fim",
              10
                  + (colunaatual * DISTANCIAX)
                  + (LARGURA * colunaatual)
                  + Math.round((LARGURA - 70) / 2),
              10 + ((nlinhas) * DISTANCIAY) + (ALTURA * nlinhas++),
              70,
              ALTURA,
              "terminador");
      graph.insertEdge(parent, null, getProximaLigacao(), ultimo, fim, "linhaquadrada");
      gerado = true;
    }
    graph.setAllowDanglingEdges(false);
    graph.setAutoSizeCells(true);
    graph.setConnectableEdges(false);
    graph.getModel().endUpdate();

    final mxGraphComponent graphComponent = new mxGraphComponent(graph);
    graphComponent.setToolTips(true);
    graphComponent.getViewport().setOpaque(true);
    graphComponent.getViewport().setBackground(new Color(250, 250, 250));
    graphComponent.setGridVisible(true);
    getContentPane().add(graphComponent);

    // Handle only mouse click events
    graphComponent
        .getGraphControl()
        .addMouseListener(
            new MouseAdapter() {

              @Override
              public void mousePressed(MouseEvent e) {
                Object cell = graphComponent.getCellAt(e.getX(), e.getY());
                if (cell != null) {
                  JanelaPrincipal.alertarClique((String) ((mxCell) cell).getValue());
                }
              }
            });

    return graphComponent;
  }
Example #7
0
  // currently not being used
  public void fitToSize() {
    double newScale = 1;

    Dimension graphSize = graphComponent.getGraphControl().getSize();
    Dimension viewPortSize = graphComponent.getViewport().getSize();

    int gw = (int) graphSize.getWidth();
    int gh = (int) graphSize.getHeight();

    if (gw > 0 && gh > 0) {
      int w = (int) viewPortSize.getWidth();
      int h = (int) viewPortSize.getHeight();

      newScale = Math.min((double) w / gw, (double) h / gh);
    }

    graphComponent.zoom(newScale);
  }
Example #8
0
 /** Test of removeVertex method, of class EventsTreeAdapter. */
 public void testRemoveVertex() {
   int width = 500, height = 500;
   System.out.println("removeVertex");
   mxGraphComponent mxGraphComponent1 = new mxGraphComponent(new mxGraph());
   mxGraphComponent1.setBounds(0, 0, width, height);
   expect(drawPanel.getComponents()).andReturn(new Component[] {mxGraphComponent1}).anyTimes();
   replay(drawPanel);
   instance.draw(drawPanel);
   instance.draw(drawPanel);
   instance.draw(drawPanel);
   instance.removeVertex(eventTreeUtil.getCellByID("" + 3));
   String str = checkIfAllGettersThrowNull("" + 3, "" + 4);
   //        assertNull(eventTreeUtil.getCellByID(""+3));
   //        assertNull(eventTreeUtil.getCellByID(""+4));
   if (str != null) {
     fail(str);
   }
   assertNull(str);
 }
  public JGraphXGraphPanel(NAR n) {
    super(new BorderLayout());

    NARGraph g = new NARGraph();
    g.add(n, IncludeEverything, new NARGraph.DefaultGraphizer(true, true, true, true, true));

    // create a visualization using JGraph, via an adapter
    jgxAdapter = new JGraphXAdapter(g) {};

    mxGraphComponent mxc = new mxGraphComponent(jgxAdapter) {};

    mxc.setAntiAlias(true);
    mxc.setConnectable(false);
    mxc.setExportEnabled(false);
    mxc.setFoldingEnabled(false);
    mxc.setPanning(true);
    mxc.setTextAntiAlias(true);

    add(new JScrollPane(mxc), BorderLayout.CENTER);

    mxFastOrganicLayout layout =
        // new mxCompactTreeLayout(jgxAdapter);
        new mxFastOrganicLayout(jgxAdapter);
    // new mxCircleLayout(jgxAdapter);
    layout.setForceConstant(150);
    layout.execute(jgxAdapter.getDefaultParent());

    /*
    mxOrganicLayout layout =
            //new mxCompactTreeLayout(jgxAdapter);
            new mxOrganicLayout(jgxAdapter);
            //new mxCircleLayout(jgxAdapter);
    layout.setEdgeLengthCostFactor(0.001);*/

    /*
    mxCompactTreeLayout layout =
            new mxCompactTreeLayout(jgxAdapter);

    layout.setLevelDistance(40);
    layout.setNodeDistance(50);
    layout.execute(jgxAdapter.getDefaultParent());*/

    jgxAdapter.setConnectableEdges(false);
    jgxAdapter.setCellsDisconnectable(false);
    jgxAdapter.setEdgeLabelsMovable(false);
    // jgxAdapter.setCellsLocked(true);
  }
Example #10
0
 // graphs the currentLayout
 public void graph() {
   if (currentLayout == FASTORGANIC) {
     layout = new mxStackLayout(panGraph, false, 10, 20, 20, 2);
     morphLayout();
     setMxLayout(currentLayout);
     morphLayout();
     layout = new mxParallelEdgeLayout(panGraph, 20);
     morphLayout();
     setMxLayout(currentLayout);
   } else if (currentLayout == CIRCLE) {
     morphLayout();
     layout = new mxParallelEdgeLayout(panGraph, 20);
     morphLayout();
     setMxLayout(currentLayout);
   } else {
     morphLayout();
   }
   graphComponent.setConnectable(false);
 }
Example #11
0
  public CellSelector(final mxGraphComponent gc, final boolean withScroll) {
    this.gc = gc;
    this.graph = gc.getGraph();
    this.view = graph.getView();
    this.model = graph.getModel();
    this.withScroll = withScroll;
    mxIEventListener updateListener =
        new mxIEventListener() {
          @Override
          public void invoke(Object sender, mxEventObject evt) {
            // System.out.println("Updating marker because of event: "+evt.getName()+" change:
            // "+evt.getProperties());

            Object changes = evt.getProperty("changes");
            if (changes != null && changes instanceof List) {
              for (Object change : ((List) changes)) {
                if (change != null && change instanceof mxStyleChange) {
                  Object cell = ((mxStyleChange) change).getCell();
                  mxCellState state = view.getState(cell, false);
                  if (currentSelectedCells.containsKey(cell)) {
                    mxCellMarker thisCellSelector = currentSelectedCells.get(cell);
                    thisCellSelector.unmark();
                    thisCellSelector.process(
                        state,
                        thisCellSelector.getMarkerColor(null, state, selectSetAsValid),
                        selectSetAsValid);
                    thisCellSelector.mark();
                  }
                }
              }
            }
            for (Entry<mxCell, mxCellMarker> el : currentSelectedCells.entrySet()) {
              el.getValue().unmark();
              el.getValue().mark();
            }
          }
        };

    view.addListener(mxEvent.SCALE_AND_TRANSLATE, updateListener);
    view.addListener(mxEvent.SCALE, updateListener);
    view.addListener(mxEvent.TRANSLATE, updateListener);
    model.addListener(mxEvent.CHANGE, updateListener);
  }
Example #12
0
 public myGraph() {
   graph = new mxGraph(); // graf "biblioteczny" na którym działamy
   component = new mxGraphComponent(graph); // component użyty w GUI,
   // zwracamy go przez
   // getComponent()
   layout = new mxHierarchicalLayout(graph); // layout dla grafu
   component.setEnabled(false); // defaultowo można klikać w wierzchołki i
   // krawędzie w GUI zaznaczając je, tutaj
   // blokuje wszystko
   //		 component.zoomTo(1, true); // początkowy zoom
   vertexWidth = 120; // wymiary prostokąta
   vertexHeight = 30;
   //		costFunction = new myCostFunction(); // funkcja potrzebna przy
   //												// findShortestPath()
   animation = null; // na razie jest null, jak będzie używana to się do
   // niej dołączy odpowiednią referencję
   animationIsPaused = false; // na początku animacja nie była jeszcze
   // pauzowana
   log = Logger.getLogger(this.getClass().getName());
 }
Example #13
0
 public void selectCell(mxCell c) {
   if (c != null) {
     mxCellMarker thisCellSelector = currentSelectedCells.get(c);
     mxCellState state = view.getState(c);
     if (thisCellSelector == null) {
       thisCellSelector = new mxCellMarker(gc);
       currentSelectedCells.put(c, thisCellSelector);
       thisCellSelector.process(
           state,
           thisCellSelector.getMarkerColor(null, state, selectSetAsValid),
           selectSetAsValid);
       thisCellSelector.mark();
       if (withScroll) gc.scrollCellToVisible(c, true);
     } else {
       thisCellSelector.process(
           state,
           thisCellSelector.getMarkerColor(null, state, selectSetAsValid),
           selectSetAsValid);
       thisCellSelector.mark();
     }
   }
 }
Example #14
0
  public Port() {
    super("Hello, World!");

    mxGraph graph =
        new mxGraph() {

          // Ports are not used as terminals for edges, they are
          // only used to compute the graphical connection point
          public boolean isPort(Object cell) {
            mxGeometry geo = getCellGeometry(cell);

            return (geo != null) ? geo.isRelative() : false;
          }

          // Implements a tooltip that shows the actual
          // source and target of an edge
          public String getToolTipForCell(Object cell) {
            if (model.isEdge(cell)) {
              return convertValueToString(model.getTerminal(cell, true))
                  + " -> "
                  + convertValueToString(model.getTerminal(cell, false));
            }

            return super.getToolTipForCell(cell);
          }

          // Removes the folding icon and disables any folding
          public boolean isCellFoldable(Object cell, boolean collapse) {
            return false;
          }
        };

    // Sets the default edge style
    Map<String, Object> style = graph.getStylesheet().getDefaultEdgeStyle();
    style.put(mxConstants.STYLE_EDGE, mxEdgeStyle.ElbowConnector);

    Object parent = graph.getDefaultParent();

    graph.getModel().beginUpdate();
    try {
      mxCell v1 = (mxCell) graph.insertVertex(parent, null, "Hello", 20, 20, 100, 100, "");
      v1.setConnectable(false);
      mxGeometry geo = graph.getModel().getGeometry(v1);
      // The size of the rectangle when the minus sign is clicked
      geo.setAlternateBounds(new mxRectangle(20, 20, 100, 50));

      mxGeometry geo1 = new mxGeometry(0, 0.5, PORT_DIAMETER, PORT_DIAMETER);
      // Because the origin is at upper left corner, need to translate to
      // position the center of port correctly
      geo1.setOffset(new mxPoint(-PORT_RADIUS, -PORT_RADIUS));
      geo1.setRelative(true);

      mxCell port1 = new mxCell(null, geo1, "shape=ellipse;perimter=ellipsePerimeter");
      port1.setVertex(true);

      mxGeometry geo2 = new mxGeometry(1.0, 0.5, PORT_DIAMETER, PORT_DIAMETER);
      geo2.setOffset(new mxPoint(-PORT_RADIUS, -PORT_RADIUS));
      geo2.setRelative(true);

      mxCell port2 = new mxCell(null, geo2, "shape=ellipse;perimter=ellipsePerimeter");
      port2.setVertex(true);

      graph.addCell(port1, v1);
      graph.addCell(port2, v1);

      Object v2 = graph.insertVertex(parent, null, "World!", 240, 150, 80, 30);

      graph.insertEdge(parent, null, "Edge", port2, v2);
    } finally {
      graph.getModel().endUpdate();
    }

    mxGraphComponent graphComponent = new mxGraphComponent(graph);
    getContentPane().add(graphComponent);
    graphComponent.setToolTips(true);
  }
Example #15
0
  public Validation() {
    super("Hello, World!");

    Document xmlDocument = mxDomUtils.createDocument();
    Element sourceNode = xmlDocument.createElement("Source");
    Element targetNode = xmlDocument.createElement("Target");
    Element subtargetNode = xmlDocument.createElement("Subtarget");

    mxGraph graph = new mxGraph();
    Object parent = graph.getDefaultParent();

    graph.getModel().beginUpdate();
    try {
      Object v1 = graph.insertVertex(parent, null, sourceNode, 20, 20, 80, 30);
      Object v2 = graph.insertVertex(parent, null, targetNode, 200, 20, 80, 30);
      Object v3 = graph.insertVertex(parent, null, targetNode.cloneNode(true), 200, 80, 80, 30);
      Object v4 = graph.insertVertex(parent, null, targetNode.cloneNode(true), 200, 140, 80, 30);
      graph.insertVertex(parent, null, subtargetNode, 200, 200, 80, 30);
      Object v6 = graph.insertVertex(parent, null, sourceNode.cloneNode(true), 20, 140, 80, 30);
      graph.insertEdge(parent, null, "", v1, v2);
      graph.insertEdge(parent, null, "", v1, v3);
      graph.insertEdge(parent, null, "", v6, v4);
      // Object e4 = graph.insertEdge(parent, null, "", v1, v4);
    } finally {
      graph.getModel().endUpdate();
    }

    mxMultiplicity[] multiplicities = new mxMultiplicity[3];

    // Source nodes needs 1..2 connected Targets
    multiplicities[0] =
        new mxMultiplicity(
            true,
            "Source",
            null,
            null,
            1,
            "2",
            Arrays.asList(new String[] {"Target"}),
            "Source Must Have 1 or 2 Targets",
            "Source Must Connect to Target",
            true);

    // Source node does not want any incoming connections
    multiplicities[1] =
        new mxMultiplicity(
            false,
            "Source",
            null,
            null,
            0,
            "0",
            null,
            "Source Must Have No Incoming Edge",
            null,
            true); // Type does not matter

    // Target needs exactly one incoming connection from Source
    multiplicities[2] =
        new mxMultiplicity(
            false,
            "Target",
            null,
            null,
            1,
            "1",
            Arrays.asList(new String[] {"Source"}),
            "Target Must Have 1 Source",
            "Target Must Connect From Source",
            true);

    graph.setMultiplicities(multiplicities);

    final mxGraphComponent graphComponent = new mxGraphComponent(graph);
    graph.setMultigraph(false);
    graph.setAllowDanglingEdges(false);
    graphComponent.setConnectable(true);
    graphComponent.setToolTips(true);

    // Enables rubberband selection
    new mxRubberband(graphComponent);
    new mxKeyboardHandler(graphComponent);

    // Installs automatic validation (use editor.validation = true
    // if you are using an mxEditor instance)
    graph
        .getModel()
        .addListener(
            mxEvent.CHANGE,
            new mxIEventListener() {
              public void invoke(Object sender, mxEventObject evt) {
                graphComponent.validateGraph();
              }
            });

    // Initial validation
    graphComponent.validateGraph();

    getContentPane().add(graphComponent);
  }
Example #16
0
  public void actionPerformed(ActionEvent e) {

    final mxGraphComponent graphComponent = trackScheme.getGUI().graphComponent;
    final mxGraph graph = trackScheme.getGraph();
    FileFilter selectedFilter = null;
    DefaultFileFilter xmlPngFilter = new DefaultFileFilter(".png", "PNG+XML file (.png)");
    FileFilter vmlFileFilter = new DefaultFileFilter(".html", "VML file (.html)");
    String filename = null;
    boolean dialogShown = false;

    String wd;

    if (lastDir != null) {
      wd = lastDir;
    } else {
      wd = System.getProperty("user.dir");
    }

    JFileChooser fc = new JFileChooser(wd);

    // Adds the default file format
    FileFilter defaultFilter = xmlPngFilter;
    fc.addChoosableFileFilter(defaultFilter);

    // Adds special vector graphics formats and HTML
    fc.addChoosableFileFilter(new DefaultFileFilter(".pdf", "PDF file (.pdf)"));
    fc.addChoosableFileFilter(new DefaultFileFilter(".svg", "SVG file (.svg)"));
    fc.addChoosableFileFilter(new DefaultFileFilter(".html", "HTML file (.html)"));
    fc.addChoosableFileFilter(vmlFileFilter);
    fc.addChoosableFileFilter(new DefaultFileFilter(".txt", "Graph Drawing file (.txt)"));
    fc.addChoosableFileFilter(new DefaultFileFilter(".mxe", "mxGraph Editor file (.mxe)"));

    // Adds a filter for each supported image format
    Object[] imageFormats = ImageIO.getReaderFormatNames();

    // Finds all distinct extensions
    HashSet<String> formats = new HashSet<String>();

    for (int i = 0; i < imageFormats.length; i++) {
      String ext = imageFormats[i].toString().toLowerCase();
      formats.add(ext);
    }

    imageFormats = formats.toArray();

    for (int i = 0; i < imageFormats.length; i++) {
      String ext = imageFormats[i].toString();
      fc.addChoosableFileFilter(
          new DefaultFileFilter("." + ext, ext.toUpperCase() + " File  (." + ext + ")"));
    }

    // Adds filter that accepts all supported image formats
    fc.addChoosableFileFilter(new DefaultFileFilter.ImageFileFilter("All Images"));
    fc.setFileFilter(defaultFilter);
    int rc = fc.showDialog(null, "Save");
    dialogShown = true;

    if (rc != JFileChooser.APPROVE_OPTION) {
      return;
    } else {
      lastDir = fc.getSelectedFile().getParent();
    }

    filename = fc.getSelectedFile().getAbsolutePath();
    selectedFilter = fc.getFileFilter();

    if (selectedFilter instanceof DefaultFileFilter) {
      String ext = ((DefaultFileFilter) selectedFilter).getExtension();

      if (!filename.toLowerCase().endsWith(ext)) {
        filename += ext;
      }
    }

    if (new File(filename).exists()
        && JOptionPane.showConfirmDialog(graphComponent, "Overwrite existing file?")
            != JOptionPane.YES_OPTION) {
      return;
    }

    try {
      String ext = filename.substring(filename.lastIndexOf('.') + 1);

      if (ext.equalsIgnoreCase("svg")) {
        mxSvgCanvas canvas =
            (mxSvgCanvas)
                mxCellRenderer.drawCells(
                    graph,
                    null,
                    1,
                    null,
                    new CanvasFactory() {
                      public mxICanvas createCanvas(int width, int height) {
                        TrackSchemeSvgCanvas canvas =
                            new TrackSchemeSvgCanvas(mxDomUtils.createSvgDocument(width, height));
                        canvas.setEmbedded(true);
                        return canvas;
                      }
                    });

        mxUtils.writeFile(mxXmlUtils.getXml(canvas.getDocument()), filename);

      } else if (selectedFilter == vmlFileFilter) {
        mxUtils.writeFile(
            mxXmlUtils.getXml(
                mxCellRenderer.createVmlDocument(graph, null, 1, null, null).getDocumentElement()),
            filename);

      } else if (ext.equalsIgnoreCase("html")) {
        mxUtils.writeFile(
            mxXmlUtils.getXml(
                mxCellRenderer.createHtmlDocument(graph, null, 1, null, null).getDocumentElement()),
            filename);

      } else if (ext.equalsIgnoreCase("mxe") || ext.equalsIgnoreCase("xml")) {
        mxCodec codec = new mxCodec();
        String xml = mxXmlUtils.getXml(codec.encode(graph.getModel()));
        mxUtils.writeFile(xml, filename);

      } else if (ext.equalsIgnoreCase("txt")) {
        String content = mxGdCodec.encode(graph); // .getDocumentString();
        mxUtils.writeFile(content, filename);

      } else if (ext.equalsIgnoreCase("pdf")) {
        exportGraphToPdf(graph, filename);

      } else {
        Color bg = null;

        if ((!ext.equalsIgnoreCase("gif") && !ext.equalsIgnoreCase("png"))
            || JOptionPane.showConfirmDialog(graphComponent, "Transparent Background?")
                != JOptionPane.YES_OPTION) {
          bg = graphComponent.getBackground();
        }

        if (selectedFilter == xmlPngFilter || (ext.equalsIgnoreCase("png") && !dialogShown)) {
          saveXmlPng(trackScheme.getGUI(), filename, bg);
        } else {
          BufferedImage image =
              mxCellRenderer.createBufferedImage(
                  graph,
                  null,
                  1,
                  bg,
                  graphComponent.isAntiAlias(),
                  null,
                  graphComponent.getCanvas());

          if (image != null) {
            ImageIO.write(image, ext, new File(filename));
          } else {
            JOptionPane.showMessageDialog(graphComponent, "No Image Data");
          }
        }
      }

    } catch (Throwable ex) {
      ex.printStackTrace();
      JOptionPane.showMessageDialog(
          graphComponent, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE);
    }
  }
Example #17
0
  /** Initialize the contents of the frame. */
  private void initialize() {
    frmPuzzledicePuzzleEditor = new JFrame();
    frmPuzzledicePuzzleEditor.setTitle("Puzzledice Puzzle Map Editor");
    frmPuzzledicePuzzleEditor.setBounds(100, 100, 743, 585);
    frmPuzzledicePuzzleEditor.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    frmPuzzledicePuzzleEditor.getContentPane().setLayout(new BorderLayout(0, 0));
    frmPuzzledicePuzzleEditor.addWindowListener(
        new WindowAdapter() {
          public void windowClosing(WindowEvent winEvt) {
            if (onExit()) System.exit(0);
          }
        });
    // Set up the program to catch OSX quit events
    try {
      OSXAdapter.setQuitHandler(this, this.getClass().getMethod("onExit", new Class[] {}));
    } catch (SecurityException e) {
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    }

    JMenuBar menuBar = new JMenuBar();
    frmPuzzledicePuzzleEditor.setJMenuBar(menuBar);

    JMenu mnFile = new JMenu("File");
    menuBar.add(mnFile);

    JMenuItem mntmNew = new JMenuItem("New");
    mntmNew.setAccelerator(
        KeyStroke.getKeyStroke(
            KeyEvent.VK_N, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    mntmNew.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
            clear();
            _openFile = null;
          }
        });
    mnFile.add(mntmNew);

    JMenuItem mntmOpen = new JMenuItem("Open");
    mntmOpen.setAccelerator(
        KeyStroke.getKeyStroke(
            KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    mntmOpen.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent evt) {

            // Run the file dialogue later since it's blocking
            SwingUtilities.invokeLater(
                new Runnable() {
                  public void run() {
                    FileDialog chooser =
                        new FileDialog(frmPuzzledicePuzzleEditor, "Open", FileDialog.LOAD);
                    chooser.setVisible(true);
                    if (chooser.getFile() != null) {
                      clear();
                      File file = new File(chooser.getDirectory(), chooser.getFile());
                      if (Loader.LoadFromXML(file)) {
                        areaEditPanel.justLoaded();
                        puzzleEditPanel.justLoaded();
                        _openFile = file;
                      } else {
                        JOptionPane.showMessageDialog(
                            frmPuzzledicePuzzleEditor,
                            "File failed to open!",
                            "Error",
                            JOptionPane.ERROR_MESSAGE);
                      }
                    }
                  }
                });
          }
        });
    mnFile.add(mntmOpen);

    JMenuItem mntmSave = new JMenuItem("Save");
    mntmSave.setAccelerator(
        KeyStroke.getKeyStroke(
            KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    mntmSave.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent arg0) {
            // Invoke the save later since it's a blocking method
            SwingUtilities.invokeLater(
                new Runnable() {
                  public void run() {
                    save();
                  }
                });
          }
        });
    mnFile.add(mntmSave);

    JMenuItem mntmSaveAs = new JMenuItem("Save As");
    mntmSaveAs.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
            SwingUtilities.invokeLater(
                new Runnable() {
                  public void run() {
                    String xml = xmlDigest();
                    saveAs(xml);
                  }
                });
          }
        });
    mnFile.add(mntmSaveAs);

    JMenuItem mntmExit = new JMenuItem("Exit");
    mntmExit.setAccelerator(
        KeyStroke.getKeyStroke(
            KeyEvent.VK_Q, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    mntmExit.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent arg0) {
            if (onExit()) System.exit(0);
          }
        });
    mnFile.add(mntmExit);

    JMenu mnHelp = new JMenu("Help");
    menuBar.add(mnHelp);

    JPanel panel = new JPanel();
    frmPuzzledicePuzzleEditor.getContentPane().add(panel);
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

    JPanel editPanel = new JPanel();
    panel.add(editPanel);
    editPanel.setLayout(new BoxLayout(editPanel, BoxLayout.X_AXIS));

    JSeparator separator_2 = new JSeparator();
    separator_2.setMinimumSize(new Dimension(5, 0));
    separator_2.setMaximumSize(new Dimension(5, 0));
    separator_2.setPreferredSize(new Dimension(5, 0));
    editPanel.add(separator_2);

    areaEditPanel = new AreaEditPanel();
    editPanel.add(areaEditPanel);

    JSeparator separator = new JSeparator();
    separator.setMinimumSize(new Dimension(5, 0));
    separator.setMaximumSize(new Dimension(5, 0));
    separator.setPreferredSize(new Dimension(5, 0));
    editPanel.add(separator);

    puzzleEditPanel = new PuzzleEditPanel();
    editPanel.add(puzzleEditPanel);

    JSeparator separator_1 = new JSeparator();
    separator_1.setMinimumSize(new Dimension(5, 0));
    separator_1.setMaximumSize(new Dimension(5, 0));
    separator_1.setPreferredSize(new Dimension(5, 0));
    editPanel.add(separator_1);

    graphPanel = new JTabbedPane(JTabbedPane.TOP);
    graphPanel.setPreferredSize(
        new Dimension(
            frmPuzzledicePuzzleEditor.getBounds().width,
            frmPuzzledicePuzzleEditor.getBounds().height));
    panel.add(graphPanel);
    graphPanel.setAlignmentY(Component.TOP_ALIGNMENT);

    areaGraph = new mxGraph();

    areaGraph.setAutoSizeCells(true);
    areaGraphComponent = new mxGraphComponent(areaGraph);
    areaGraphComponent.addComponentListener(
        new ComponentAdapter() {
          @Override
          public void componentResized(ComponentEvent arg0) {
            areaGraphLayout =
                new mxOrganicLayout(
                    areaGraph,
                    new Rectangle(
                        0, 0, graphPanel.getBounds().width, graphPanel.getBounds().height));
            areaGraphLayout.execute(areaGraph.getDefaultParent());
          }
        });
    areaGraphComponent.setEnabled(false);
    areaGraphLayout =
        new mxOrganicLayout(
            areaGraph,
            new Rectangle(0, 0, graphPanel.getBounds().width, graphPanel.getBounds().height));

    areaGraph.setEnabled(false);

    graphPanel.addTab("Area Graph", null, areaGraphComponent, null);

    puzzleGraph = new mxGraph();

    puzzleGraph.setAutoSizeCells(true);

    puzzleGraphComponent = new mxGraphComponent(puzzleGraph);
    puzzleGraphComponent.addComponentListener(
        new ComponentAdapter() {
          @Override
          public void componentResized(ComponentEvent arg0) {}
        });
    puzzleGraphComponent.setEnabled(false);
    puzzleGraphOrganicLayout =
        new mxOrganicLayout(
            puzzleGraph,
            new Rectangle(0, 0, graphPanel.getBounds().width, graphPanel.getBounds().height));
    puzzleGraphHierLayout = new mxHierarchicalLayout(puzzleGraph, SwingConstants.WEST);

    graphPanel.addTab("Puzzle Graph", null, puzzleGraphComponent, null);
    txtTextPanel = new JTextArea("Textual description");
    panel.add(txtTextPanel);
    txtTextPanel.setLineWrap(true);
    txtTextPanel.setWrapStyleWord(true);
    txtTextPanel.setEditable(false);

    frmPuzzledicePuzzleEditor.addComponentListener(
        new ComponentAdapter() {
          @Override
          public void componentResized(ComponentEvent arg0) {
            graphPanel.setPreferredSize(
                new Dimension(
                    frmPuzzledicePuzzleEditor.getBounds().width,
                    frmPuzzledicePuzzleEditor.getBounds().height));
          }
        });

    _emptyXml = xmlDigest();
  }
  @SuppressWarnings("serial")
  public JTableRenderer(final Object cell, final mxGraphComponent graphContainer) {
    this.cell = cell;
    this.graphContainer = graphContainer;
    this.graph = graphContainer.getGraph();
    setLayout(new BorderLayout());
    setBorder(
        BorderFactory.createCompoundBorder(
            ShadowBorder.getSharedInstance(), BorderFactory.createBevelBorder(BevelBorder.RAISED)));

    JPanel title = new JPanel();
    title.setBackground(new Color(149, 173, 239));
    title.setOpaque(true);
    title.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 1));
    title.setLayout(new BorderLayout());

    JLabel icon =
        new JLabel(new ImageIcon(JTableRenderer.class.getResource(IMAGE_PATH + "preferences.gif")));
    icon.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 1));
    title.add(icon, BorderLayout.WEST);

    JLabel label = new JLabel(String.valueOf(graph.getLabel(cell)));
    label.setForeground(Color.WHITE);
    label.setFont(title.getFont().deriveFont(Font.BOLD, 11));
    label.setBorder(BorderFactory.createEmptyBorder(0, 1, 0, 2));
    title.add(label, BorderLayout.CENTER);

    JPanel toolBar2 = new JPanel();
    toolBar2.setLayout(new FlowLayout(FlowLayout.LEFT, 1, 2));
    toolBar2.setOpaque(false);
    JButton button =
        new JButton(
            new AbstractAction(
                "", new ImageIcon(JTableRenderer.class.getResource(IMAGE_PATH + "minimize.gif"))) {

              public void actionPerformed(ActionEvent e) {
                graph.foldCells(graph.isCellCollapsed(cell), false, new Object[] {cell});
                ((JButton) e.getSource())
                    .setIcon(
                        new ImageIcon(
                            JTableRenderer.class.getResource(
                                IMAGE_PATH
                                    + ((graph.isCellCollapsed(cell))
                                        ? "maximize.gif"
                                        : "minimize.gif"))));
              }
            });
    button.setPreferredSize(new Dimension(16, 16));
    button.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    button.setToolTipText("Collapse/Expand");
    button.setOpaque(false);
    toolBar2.add(button);

    title.add(toolBar2, BorderLayout.EAST);
    add(title, BorderLayout.NORTH);

    // CellStyle style =
    // graph.getStylesheet().getCellStyle(graph.getModel(),
    // cell);
    // if (style.getStyleClass() == null) {
    table = new MyTable();
    JScrollPane scrollPane = new JScrollPane(table);
    scrollPane.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

    if (graph.getModel().getChildCount(cell) == 0) {
      scrollPane.getViewport().setBackground(Color.WHITE);
      setOpaque(true);
      add(scrollPane, BorderLayout.CENTER);
    }

    scrollPane
        .getVerticalScrollBar()
        .addAdjustmentListener(
            new AdjustmentListener() {

              public void adjustmentValueChanged(AdjustmentEvent e) {
                graphContainer.refresh();
              }
            });

    label = new JLabel(new ImageIcon(JTableRenderer.class.getResource(IMAGE_PATH + "resize.gif")));
    label.setCursor(new Cursor(Cursor.NW_RESIZE_CURSOR));

    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.add(label, BorderLayout.EAST);

    add(panel, BorderLayout.SOUTH);

    ResizeHandler resizeHandler = new ResizeHandler();
    label.addMouseListener(resizeHandler);
    label.addMouseMotionListener(resizeHandler);

    setMinimumSize(new Dimension(20, 30));
  }
Example #19
0
  /**
   * Dibuja el árbol de la expresión regular como grafo.
   *
   * @return Imagen representando el árbol de la expresión regular.
   */
  public BufferedImage imagen() {
    if (this.imagen == null) {
      mxGraph graph = new mxGraph();
      Object parent = graph.getDefaultParent();
      Map<ExpresionRegular, Object> gNodos = new HashMap<>();
      ExpresionRegular actual;
      Object gNodo, gActual;
      List<ExpresionRegular> siguientes = new ArrayList<>();
      boolean tieneHijoIzquierdo, tieneHijoDerecho;

      String estiloVertex = "shape=ellipse;fillColor=white;strokeColor=black;fontColor=black;";
      String estiloEdge =
          "strokeColor=black;fontColor=black;labelBackgroundColor=white;endArrow=open;";

      graph.getModel().beginUpdate();
      try {
        siguientes.add(this);

        while (!siguientes.isEmpty()) {
          actual = siguientes.get(0);

          if (!gNodos.containsKey(actual)) {
            gActual = graph.insertVertex(parent, null, actual.tipo(), 0, 0, 30, 30, estiloVertex);
            gNodos.put(actual, gActual);
          } else {
            gActual = gNodos.get(actual);
          }

          tieneHijoIzquierdo = !actual.esSimbolo() && !actual.esVacio();
          tieneHijoDerecho = tieneHijoIzquierdo && !actual.esCierre();

          if (tieneHijoIzquierdo) {
            siguientes.add(actual.hijoIzquierdo());
            gNodo =
                graph.insertVertex(
                    parent, null, actual.hijoIzquierdo().tipo(), 0, 0, 30, 30, estiloVertex);
            graph.insertEdge(parent, null, "", gActual, gNodo, estiloEdge);
            gNodos.put(actual.hijoIzquierdo(), gNodo);
          }

          if (tieneHijoDerecho) {
            siguientes.add(actual.hijoDerecho());
            gNodo =
                graph.insertVertex(
                    parent, null, actual.hijoDerecho().tipo(), 0, 0, 30, 30, estiloVertex);
            graph.insertEdge(parent, null, "", gActual, gNodo, estiloEdge);
            gNodos.put(actual.hijoDerecho(), gNodo);
          }

          siguientes.remove(actual);
        }
      } finally {
        graph.getModel().endUpdate();

        mxGraphComponent graphComponent = new mxGraphComponent(graph);

        new mxHierarchicalLayout(graph, SwingConstants.NORTH).execute(parent);
        new mxParallelEdgeLayout(graph).execute(parent);

        this.imagen =
            mxCellRenderer.createBufferedImage(
                graph,
                null,
                1,
                Color.WHITE,
                graphComponent.isAntiAlias(),
                null,
                graphComponent.getCanvas());
      }
    }

    return this.imagen;
  }