Ejemplo n.º 1
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();
    }
  }
Ejemplo n.º 2
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;
  }
Ejemplo n.º 3
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);
    }
  }