Exemplo n.º 1
0
		@Override
		public void actionPerformed(ActionEvent e) {

			int returnVal = fileChooser.showOpenDialog(FileSelectPanel.this);

			if (returnVal == JFileChooser.APPROVE_OPTION) {
				File selectedFile = fileChooser.getSelectedFile();

				try {
					getFileNameField().setText(selectedFile.getCanonicalPath());
				} catch (IOException e1) {
					getFileNameField().setText("");
				}

				if (fileChooser.getFileFilter() instanceof FileNameExtensionFilter)
				{
					FileNameExtensionFilter filter = (FileNameExtensionFilter) fileChooser.getFileFilter();
					String extension = filters.get(filter.getDescription())[0];

					if (!getFileNameField().getText().endsWith(extension))
						getFileNameField().setText(getFileNameField().getText() + "." + extension);
				}

				if (returnRelativePath) {
					getFileNameField().setText(getRelativePath(getFileNameField().getText()));
				}
			}

		}
Exemplo n.º 2
0
 /** Shows a file dialog and opens a drawing. */
 public void promptOpen() {
   toolDone();
   JFileChooser openDialog = createOpenFileChooser();
   getStorageFormatManager().registerFileFilters(openDialog);
   if (openDialog.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
     StorageFormat foundFormat =
         getStorageFormatManager().findStorageFormat(openDialog.getFileFilter());
     if (foundFormat != null) {
       loadDrawing(foundFormat, openDialog.getSelectedFile().getAbsolutePath());
     } else {
       showStatus("Not a valid file format: " + openDialog.getFileFilter().getDescription());
     }
   }
 }
Exemplo n.º 3
0
  /** Handles the saving of a drawing to a file. */
  private void doSave() {
    JFileChooser chooser = new JFileChooser(getClass().getResource("").getFile());
    chooser.setDialogTitle("Save Graphic");
    chooser.setDialogType(JFileChooser.SAVE_DIALOG);
    FileFilter filter =
        new FileFilter() {
          @Override
          public String getDescription() {
            return "JDraw Graphic (*.draw)";
          }

          @Override
          public boolean accept(File f) {
            return f.getName().endsWith(".draw");
          }
        };
    chooser.setFileFilter(filter);
    int res = chooser.showOpenDialog(this);

    if (res == JFileChooser.APPROVE_OPTION) {
      // save graphic
      File file = chooser.getSelectedFile();
      if (chooser.getFileFilter() == filter && !filter.accept(file)) {
        file = new File(chooser.getCurrentDirectory(), file.getName() + ".draw");
      }
      System.out.println("save current graphic to file " + file.getName());
    }
  }
Exemplo n.º 4
0
 private void saveSrc() {
   fileChooser.resetChoosableFileFilters();
   fileChooser.addChoosableFileFilter(asmFilter);
   fileChooser.setFileFilter(asmFilter);
   if (fileChooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
     try {
       File file = fileChooser.getSelectedFile();
       if (fileChooser.getFileFilter() == asmFilter && !asmFilter.accept(file)) {
         file = new File(file.getAbsolutePath() + asmFilter.getExtensions()[0]);
       }
       if (file.exists()) {
         if (JOptionPane.showConfirmDialog(
                 frame, "File exists. Overwrite?", "Confirm", JOptionPane.YES_NO_OPTION)
             != JOptionPane.YES_OPTION) {
           return;
         }
       }
       PrintStream output = new PrintStream(file);
       output.print(sourceTextarea.getText());
       output.close();
     } catch (IOException e1) {
       JOptionPane.showMessageDialog(
           frame, "Unable to open file", "Error", JOptionPane.ERROR_MESSAGE);
       e1.printStackTrace();
     }
   }
 }
  private String chooseFileName(boolean ownXmlFormat, FileFilter filefilter) {
    String fileName = null;

    // filechooser must be recreated to avoid a bug where getSelectedFile() was null (if a file is
    // saved more than one time by doubleclicking on an existing file)
    reloadSaveFileChooser();

    setAvailableFileFilters(ownXmlFormat);
    saveFileChooser.setFileFilter(filefilter);

    int returnVal = saveFileChooser.showSaveDialog(Main.getInstance().getGUI());
    if (returnVal == JFileChooser.APPROVE_OPTION) {

      File selectedFileWithExt =
          new File(
              saveFileChooser.getSelectedFile().getName()
                  + "."
                  + fileextensions.get(saveFileChooser.getFileFilter()));
      // We must check for the file with and without extension (saving without adding the extension
      // automatically adds the selected extension)
      if (saveFileChooser.getSelectedFile().exists() || selectedFileWithExt.exists()) {
        int overwriteQuestionResult =
            JOptionPane.showConfirmDialog(
                Main.getInstance().getGUI(),
                "File already exists! Overwrite?",
                "Overwrite File",
                JOptionPane.YES_NO_OPTION);
        if (overwriteQuestionResult == JOptionPane.NO_OPTION)
          return chooseFileName(ownXmlFormat, filefilter);
      }
      fileName = saveFileChooser.getSelectedFile().getAbsolutePath();
    }
    return fileName;
  }
Exemplo n.º 6
0
 private void saveBin() {
   fileChooser.resetChoosableFileFilters();
   fileChooser.addChoosableFileFilter(binFilter);
   fileChooser.setFileFilter(binFilter);
   if (fileChooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
     try {
       File file = fileChooser.getSelectedFile();
       if (fileChooser.getFileFilter() == binFilter && !binFilter.accept(file)) {
         file = new File(file.getAbsolutePath() + binFilter.getExtensions()[0]);
       }
       if (file.exists()) {
         if (JOptionPane.showConfirmDialog(
                 frame, "File exists. Overwrite?", "Confirm", JOptionPane.YES_NO_OPTION)
             != JOptionPane.YES_OPTION) {
           return;
         }
       }
       FileOutputStream output = new FileOutputStream(file);
       for (char i : binary) {
         output.write(i & 0xff);
         output.write((i >> 8) & 0xff);
       }
       output.close();
     } catch (IOException e1) {
       JOptionPane.showMessageDialog(
           frame, "Unable to open file", "Error", JOptionPane.ERROR_MESSAGE);
       e1.printStackTrace();
     }
   }
 }
  /** Show the save dialog to save the network file. */
  private void saveEvent() {
    JFileChooser fileSaver = new JFileChooser(inpFile.getParent());
    fileSaver.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fileSaver.setAcceptAllFileFilterUsed(false);
    fileSaver.addChoosableFileFilter(new XLSXFilter());
    fileSaver.addChoosableFileFilter(new XMLFilter());
    fileSaver.addChoosableFileFilter(new INPFilter());

    fileSaver.showSaveDialog(frame);

    if (fileSaver.getSelectedFile() == null) return;

    Network.FileType netType = Network.FileType.INP_FILE;

    if (fileSaver.getFileFilter() instanceof XLSXFilter) {
      netType = Network.FileType.EXCEL_FILE;
    } else if (fileSaver.getFileFilter() instanceof XMLFilter) {
      netType = Network.FileType.XML_FILE;
      JOptionPane.showMessageDialog(frame, "Not supported yet !", "Error", JOptionPane.OK_OPTION);
      return;
    }

    OutputComposer compose = OutputComposer.create(netType);

    String extension = "";

    if (Utilities.getFileExtension(fileSaver.getSelectedFile().getName()).equals(""))
      switch (netType) {
        case INP_FILE:
          extension = ".inp";
          break;
        case EXCEL_FILE:
          extension = ".xlsx";
          break;
        case XML_FILE:
          extension = ".xml";
          break;
      }

    try {
      compose.composer(
          epanetNetwork, new File(fileSaver.getSelectedFile().getAbsolutePath() + extension));
    } catch (ENException e1) {
      e1.printStackTrace();
    }
  }
Exemplo n.º 8
0
 @Override
 public void actionPerformed(ActionEvent e) {
   JFileChooser fc = createAndOpenFileChooser(true, true, null);
   if (fc == null) return;
   File[] files = fc.getSelectedFiles();
   OpenFileTask task = new OpenFileTask(Arrays.asList(files), fc.getFileFilter());
   task.setRecordHistory(true);
   Main.worker.submit(task);
 }
Exemplo n.º 9
0
 private void resetGlobFilter() {
   if (actualFileFilter != null) {
     JFileChooser chooser = getFileChooser();
     FileFilter currentFilter = chooser.getFileFilter();
     if (currentFilter != null && currentFilter.equals(globFilter)) {
       chooser.setFileFilter(actualFileFilter);
       chooser.removeChoosableFileFilter(globFilter);
     }
     actualFileFilter = null;
   }
 }
  public ExportStatisticsFile(List<MyObjectStatistics> valores) {

    JFileChooser jfc = new JFileChooser(lastPath);
    jfc.removeChoosableFileFilter(jfc.getAcceptAllFileFilter());

    // Adding required extensions (dbf, csv)
    dbfExtensionsSupported = new Hashtable<String, MyFileFilter>();
    csvExtensionsSupported = new Hashtable<String, MyFileFilter>();
    dbfExtensionsSupported.put(
        "dbf", new MyFileFilter("dbf", PluginServices.getText(this, "Ficheros_dbf"), "dbf"));
    csvExtensionsSupported.put(
        "csv", new MyFileFilter("csv", PluginServices.getText(this, "Ficheros_csv"), "csv"));

    Iterator<MyFileFilter> iter = csvExtensionsSupported.values().iterator();
    while (iter.hasNext()) {
      jfc.addChoosableFileFilter(iter.next());
    }

    iter = dbfExtensionsSupported.values().iterator();
    while (iter.hasNext()) {
      jfc.addChoosableFileFilter(iter.next());
    }

    // Opening a JFileCooser
    if (jfc.showSaveDialog((Component) PluginServices.getMainFrame())
        == JFileChooser.APPROVE_OPTION) {
      File endFile = jfc.getSelectedFile();
      if (endFile.exists()) { // File exists in the directory.
        int resp =
            JOptionPane.showConfirmDialog(
                (Component) PluginServices.getMainFrame(),
                PluginServices.getText(this, "fichero_ya_existe_seguro_desea_guardarlo")
                    + "\n"
                    + endFile.getAbsolutePath(),
                PluginServices.getText(this, "guardar"),
                JOptionPane.YES_NO_OPTION); // Informing the user
        if (resp != JOptionPane.YES_OPTION) { // cancel pressed.
          return;
        }
      } // end if exits.
      MyFileFilter filter = (MyFileFilter) jfc.getFileFilter(); // dbf, csv
      endFile = filter.normalizeExtension(endFile); // "name" + "." +
      // "dbf", "name" +
      // "." + "csv"

      if (filter.getExtensionOfAFile(endFile).toLowerCase().compareTo("csv") == 0) { // csv file
        exportToCSVFile(valores, endFile); // export to csv format
      } else if (filter.getExtensionOfAFile(endFile).toLowerCase().compareTo("dbf")
          == 0) { // dbf file
        exportToDBFFile(valores, endFile); // export to dbf format
      }
    } // end if aprove option.
  }
Exemplo n.º 11
0
  private void saveProject() {
    if (file == null) {
      JFileChooser fileChooser = new JFileChooser();
      fileChooser.addChoosableFileFilter(new GenericFileFilter(".atp", "Arduino Trend Progetto"));
      int n = fileChooser.showSaveDialog(view);

      if (n == JFileChooser.APPROVE_OPTION) {
        file = fileChooser.getSelectedFile();
        String nameFile = file.getName();
        FileFilter currentFilter = fileChooser.getFileFilter();
        if (currentFilter instanceof GenericFileFilter) {
          String ext = ((GenericFileFilter) currentFilter).getExtension();
          if (file.getName().endsWith(ext) == false) {
            try {
              file = new File(file.getCanonicalPath() + ext);
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
        int a = JOptionPane.OK_OPTION;
        if (file.exists()) {
          a = JOptionPane.showConfirmDialog(view, "Vuoi sovrascire il file?");
        }
        switch (a) {
          case JOptionPane.OK_OPTION:
            try {
              project.setTitle(nameFile);
              view.setTitle(nameFile);
              project.save(file, pens, view.trend.getModel());
              fileEdited = false;
            } catch (IOException e) {
              view.popupErrorMessage(e.getMessage());
              e.printStackTrace();
            }
            break;
          case JOptionPane.NO_OPTION:
            saveProject();
            break;
          case JOptionPane.CANCEL_OPTION:
            break;
        }
      }
    } else {
      try {
        project.save(file, pens, view.trend.getModel());
        fileEdited = false;
      } catch (IOException e) {
        view.popupErrorMessage(e.getMessage());
        e.printStackTrace();
      }
    }
  }
  public void doSaveAs(String fileextension) throws IOException {
    String fileName =
        this.chooseFileName(fileextension.equals(Program.EXTENSION), filters.get(fileextension));
    String extension = this.fileextensions.get(saveFileChooser.getFileFilter());
    if (fileName == null) return; // If the filechooser has been closed without saving
    if (!fileName.endsWith("." + extension)) fileName += "." + extension;

    File fileToSave = new File(fileName);
    if (extension.equals(Program.EXTENSION)) {
      this.file = fileToSave;
      this.setFileName(this.file.getName());
      save(true);
    } else doExportAs(extension, fileToSave);
  }
Exemplo n.º 13
0
 private static File checkFileAndConfirmOverWrite(JFileChooser fc, String extension) {
   if (fc == null) return null;
   File file = fc.getSelectedFile();
   String fn = file.getPath();
   if (fn.indexOf('.') == -1) {
     FileFilter ff = fc.getFileFilter();
     if (ff instanceof ExtensionFileFilter) {
       fn += "." + ((ExtensionFileFilter) ff).getDefaultExtension();
     } else if (extension != null) {
       fn += "." + extension;
     }
     file = new File(fn);
     if (!confirmOverwrite(file)) return null;
   }
   return file;
 }
Exemplo n.º 14
0
  private void exportProjectAndData() {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setApproveButtonText("Esporta");
    fileChooser.setDialogTitle("Esporta progetto e dati");
    fileChooser.addChoosableFileFilter(new GenericFileFilter(".csv", "File generico csv"));
    fileChooser.addChoosableFileFilter(new GenericFileFilter(".atd", "Arduino Trend Data"));

    int n = fileChooser.showSaveDialog(view);

    if (n == JFileChooser.APPROVE_OPTION) {
      File file = fileChooser.getSelectedFile();
      FileFilter currentFilter = fileChooser.getFileFilter();
      if (currentFilter instanceof GenericFileFilter) {
        String ext = ((GenericFileFilter) currentFilter).getExtension();
        if (file.getName().endsWith(ext) == false) {
          try {
            file = new File(file.getCanonicalPath() + ext);
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
      int a = JOptionPane.OK_OPTION;
      if (file.exists()) {
        a = JOptionPane.showConfirmDialog(view, "Vuoi sovrascire il file?");
      }
      switch (a) {
        case JOptionPane.OK_OPTION:
          try {
            project.exportProject(file, pens, view.trend.getModel());
          } catch (IOException e) {
            view.popupErrorMessage(e.getMessage());
            e.printStackTrace();
          }
          break;
        case JOptionPane.NO_OPTION:
          exportProjectAndData();
          break;
        case JOptionPane.CANCEL_OPTION:
          System.out.println("CANCEL");
          break;
      }
    }
  }
Exemplo n.º 15
0
  /**
   * Creates a JFileChooser dialog for the user to select a plain text file to save as (either by
   * clicking on a file or by typing in a filename).
   */
  private void fileSaveAs() {
    JFileChooser saveAsDialog = new JFileChooser();
    saveAsDialog.setFileFilter(new FileNameExtensionFilter("Plain Text Files (*.txt)", "txt"));
    saveAsDialog.setFileSelectionMode(JFileChooser.FILES_ONLY);
    saveAsDialog.setMultiSelectionEnabled(false);
    if (currentFile != null && currentFile.exists()) {
      saveAsDialog.setSelectedFile(currentFile);
      saveAsDialog.setCurrentDirectory(currentFile);
    }

    int returnVal = saveAsDialog.showSaveDialog(mainFrame);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
      PrintStream saveAsStream = null;
      try {
        if (saveAsDialog.getFileFilter().getDescription().equals("Plain Text Files (*.txt)")
            && !saveAsDialog.getSelectedFile().getName().contains(".txt")) {
          saveAsStream =
              new PrintStream(new File(saveAsDialog.getSelectedFile().getPath() + ".txt"));
        } else {
          saveAsStream = new PrintStream(saveAsDialog.getSelectedFile());
        }
        saveAsStream.print(editor.getText());
        if (currentFile == null
            || !saveAsDialog
                .getSelectedFile()
                .getAbsolutePath()
                .equals(currentFile.getAbsolutePath())) {
          currentFile = new File(saveAsDialog.getSelectedFile().getPath() + ".txt");
          try {
            mainFrame.setTitle(programName + " - " + currentFile.getCanonicalPath());
          } catch (IOException ex) {
            mainFrame.setTitle(programName + " - " + currentFile.getName());
          }
        }
        save.setEnabled(true);
      } catch (FileNotFoundException ex) {
        fileSaveAs();
      } finally {
        saveAsStream.close();
      }
    } else if (returnVal == JFileChooser.CANCEL_OPTION) {
    } else if (returnVal == JFileChooser.ERROR_OPTION) {
    }
  }
Exemplo n.º 16
0
 /**
  * Prompts the user for a filename and saves the model to the selected file
  *
  * @return A flag that indicates whether the file could be written successfully.
  */
 public boolean saveAs() {
   JFileChooser fileChooser = new JFileChooser();
   // FileFilter binaryFormatFilter = SuffixFileFilter.BINARY;
   // fileChooser.addChoosableFileFilter(binaryFormatFilter);
   fileChooser.setFileFilter(SuffixFileFilter.XML);
   if (model.getFile() != null) {
     fileChooser.setSelectedFile(model.getFile());
   } else {
     fileChooser.setSelectedFile(new File(getName()));
   }
   int retVal = fileChooser.showSaveDialog(this);
   if (retVal == JFileChooser.APPROVE_OPTION) {
     File selectedFile = fileChooser.getSelectedFile();
     selectedFile = ((SuffixFileFilter) fileChooser.getFileFilter()).makeAcceptable(selectedFile);
     model.setFile(selectedFile);
     model.setName(null);
     if (selectedFile.exists()) {
       if (selectedFile.canWrite()) {
         int chosen =
             JOptionPane.showConfirmDialog(
                 this,
                 Messages.getString("Main.11"),
                 Messages.getString("Main.12"),
                 JOptionPane.YES_NO_OPTION,
                 JOptionPane.QUESTION_MESSAGE); // $NON-NLS-1$ //$NON-NLS-2$
         if (chosen == JOptionPane.NO_OPTION) {
           return false;
         }
       } else {
         JOptionPane.showMessageDialog(
             this,
             Messages.getString("Main.13"),
             Messages.getString("Main.14"),
             JOptionPane.ERROR_MESSAGE); // $NON-NLS-1$ //$NON-NLS-2$
         return false;
       }
     }
     return writeFile();
   } else {
     return false;
   }
 }
Exemplo n.º 17
0
  /**
   * Shows the image export dialog and processes the results.
   *
   * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
   */
  public void actionPerformed(ActionEvent evt) {
    // lazy initialization
    if (chooser == null) init();

    // open image save dialog
    File f = null;
    scaler.setImage(display.getOffscreenBuffer());
    int returnVal = chooser.showSaveDialog(display);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
      f = chooser.getSelectedFile();
    } else {
      return;
    }
    String format = ((SimpleFileFilter) chooser.getFileFilter()).getExtension();
    String ext = IOLib.getExtension(f);
    if (!format.equals(ext)) {
      f = new File(f.toString() + "." + format);
    }

    double scale = scaler.getScale();

    // save image
    boolean success = false;
    try {
      OutputStream out = new BufferedOutputStream(new FileOutputStream(f));
      System.out.print("Saving image " + f.getName() + ", " + format + " format...");
      success = display.saveImage(out, format, scale);
      out.flush();
      out.close();
      System.out.println("\tDONE");
    } catch (Exception e) {
      success = false;
    }
    // show result dialog on failure
    if (!success) {
      JOptionPane.showMessageDialog(
          display, "Error Saving Image!", "Image Save Error", JOptionPane.ERROR_MESSAGE);
    }
  }
  // TODO mejora serializable guardar
  public static void guardarTXT(MiJTextPane mjt) throws IOException {
    JFileChooser file = new JFileChooser();
    // TODO mejora de utilizar extensión para guardar por defecto
    FileNameExtensionFilter filtroExtensionDVD =
        new FileNameExtensionFilter("Texto(*.dvd)", "*.dvd");
    file.setFileFilter(filtroExtensionDVD);
    FileNameExtensionFilter filtroExtensionTXT =
        new FileNameExtensionFilter("Texto(*.txt2)", "*.txt2");
    file.addChoosableFileFilter(filtroExtensionTXT);

    int usuarioSelection = file.showSaveDialog(null);
    if (usuarioSelection == JFileChooser.APPROVE_OPTION) {
      FileFilter extension = file.getFileFilter();
      String ruta = file.getSelectedFile().getPath();
      System.out.println(extension);
      FileOutputStream fos = new FileOutputStream(ruta + ".sss");
      ObjectOutputStream out = new ObjectOutputStream(fos);
      out.writeObject(mjt);
      out.flush();
      out.close();
      fos.close();
    }
  }
Exemplo n.º 19
0
 public FileFilter getFileFilter() {
   return jfc.getFileFilter();
 }
Exemplo n.º 20
0
  @Override
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == open) {
      if (isInProgress()) {
        systemIsBusy();
        return;
      }

      checkRunned();

      chooser = new JFileChooser();
      chooser.setAcceptAllFileFilterUsed(false);
      chooser.setFileFilter(new InputFileFilter(false));
      if (loadedFile != null) chooser.setSelectedFile(loadedFile);
      int returnValue = chooser.showOpenDialog(this);
      if (returnValue == JFileChooser.APPROVE_OPTION) {
        boolean approved =
            ((InputFileFilter) chooser.getFileFilter()).isFileApproved(chooser.getSelectedFile());
        if (approved) {
          startProgress();
          new MultiThread(
                  new Runnable() {
                    public void run() {
                      try {

                        loadedFile = chooser.getSelectedFile();
                        FileInputStream fis = new FileInputStream(loadedFile);
                        InputParser ip = new InputParser(fis);
                        if (ip.parseInput()) {
                          field = new Field(new ArrayList<Point>(Arrays.asList(ip.getPoints())));
                          minAlgo.setText(String.valueOf(ip.minimumClusters));
                          maxAlgo.setText(String.valueOf(ip.maximumClusters));
                        }
                      } catch (FileNotFoundException e1) {
                      }
                      contentpanel.center();
                      stopProgress();
                    }
                  })
              .start();
        }
      }
    } else if (e.getSource() == center) {
      if (isInProgress()) {
        systemIsBusy();
        return;
      }

      startProgress();
      new MultiThread(
              new Runnable() {
                public void run() {
                  contentpanel.removeMouseWheelListener(contentpanel);
                  contentpanel.center();
                  contentpanel.addMouseWheelListener(contentpanel);
                  stopProgressRepaint();
                }
              })
          .start();
    } else if (e.getSource() == save) {
      if (isInProgress()) {
        systemIsBusy();
        return;
      }

      checkRunned();

      chooser = new JFileChooser();
      chooser.setAcceptAllFileFilterUsed(false);
      chooser.setFileFilter(new InputFileFilter(true));
      if (loadedFile != null) chooser.setSelectedFile(loadedFile);
      int returnValue = chooser.showSaveDialog(this);
      if (returnValue == JFileChooser.APPROVE_OPTION) {
        boolean approved =
            ((InputFileFilter) chooser.getFileFilter()).isFileApproved(chooser.getSelectedFile());
        if (approved) {
          loadedFile = chooser.getSelectedFile();
          boolean halt = loadedFile.exists();
          if (halt) {
            int i =
                JOptionPane.showInternalConfirmDialog(
                    c,
                    "Are you sure you want to override this file?",
                    "Warning",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE);
            if (i == JOptionPane.YES_OPTION) {
              halt = false;
            }
          }

          if (!halt) {
            try {
              PrintWriter pw = new PrintWriter(new FileWriter(loadedFile));
              pw.println("find " + field.getNumberOfClusters() + " clusters");
              pw.println(field.size() + " points");
              Object[] obj = field.toArray();
              for (int i = 0; i < obj.length; i++) {
                Point p = (Point) obj[i];
                pw.println(p.getX() + " " + p.getY());
              }
              pw.close();
            } catch (IOException e1) {
            }
          }
        }
      }
    } else if (e.getSource() == clear) {
      if (isInProgress()) {
        systemIsBusy();
        return;
      }

      int i =
          JOptionPane.showInternalConfirmDialog(
              c,
              "Are you sure you want to clear the field?",
              "Warning",
              JOptionPane.YES_NO_OPTION,
              JOptionPane.WARNING_MESSAGE);

      checkRunned();
      if (i == JOptionPane.YES_OPTION) {
        field = new Field();
        updateContentPanel();
      }
    } else if (e.getSource() == circle) {
      contentpanel.setSelectionMode(ContentPanel.SELECT_CIRCLE);
    } else if (e.getSource() == square) {
      contentpanel.setSelectionMode(ContentPanel.SELECT_SQUARE);
    } else if (e.getSource() == addacluster) {
      if (isInProgress()) {
        systemIsBusy();
        return;
      }

      checkRunned();

      contentpanel.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
    } else if (e.getSource() == addnoise) {
      if (isInProgress()) {
        systemIsBusy();
        return;
      }

      checkRunned();
      final String s =
          JOptionPane.showInternalInputDialog(
              c, "How many points?", "Add noise", JOptionPane.QUESTION_MESSAGE);

      startProgress();
      new MultiThread(
              new Runnable() {
                public void run() {
                  if (s != null) {
                    int number;
                    try {
                      number = Integer.parseInt(s);
                    } catch (Exception ex) {
                      number = 0;
                    }

                    int tillX = 1000000000;
                    int tillY = 1000000000;
                    int addX = 0;
                    int addY = 0;
                    if (inRectangle.isSelected()) {
                      Rectangle r = field.getBoundingRectangle();
                      if (!(r.x1 == 0 && r.y1 == 0 && r.x2 == 0 && r.y2 == 0)) {
                        tillX = r.x2 - r.x1;
                        addX = r.x1;
                        tillY = r.y2 - r.y1;
                        addY = r.y1;
                      } else {
                        tillX = 500000000;
                        tillY = 500000000;
                      }
                    }

                    for (int i = 0; i < number; i++) {
                      int x = random.nextInt(tillX);
                      x += addX;
                      int y;

                      boolean busy = true;
                      while (busy) {
                        y = random.nextInt(tillY);
                        y += addY;
                        boolean inside = false;
                        Object[] array = field.toArray();
                        for (int j = 0; j < field.size(); j++) {
                          if (((Point) array[j]).compareTo(x, y)) {
                            inside = true;
                            break;
                          }
                        }

                        if (!inside) {
                          field.add(new Point(x, y));
                          busy = false;
                        }
                      }
                    }
                  }
                  stopProgress();
                }
              })
          .start();
    } else if (e.getSource() == run) {
      if (isInProgress()) {
        systemIsBusy();
        return;
      }

      checkRunned();

      startProgress();

      runAlgo();
    }
  }
Exemplo n.º 21
0
  @Override
  public void run(ImageProcessor arg0) {

    JFileChooser fc = this.createFileChooser();

    // set image title (without extension) as default file name
    String origtitle = null;
    if (this.img != null) origtitle = this.img.getTitle();
    else if (this.imp != null) origtitle = this.imp.getTitle();
    if (origtitle != null) {
      int dotID = origtitle.indexOf(".");
      if (dotID != -1) {
        String name = origtitle.substring(0, dotID);
        fc.setSelectedFile(new File(name + ".ome.tiff"));
      }
    }

    while (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {

      File outfile = fc.getSelectedFile();

      if (outfile == null) {
        IJ.error("File save dialog returned 'null'");
        return;
      }

      // if a specific format file filter was chosen, but the selected filename does not
      // match the formats extension, add the extension
      FileFilter ff = fc.getFileFilter();
      if (ff instanceof ExtensionFileFilter) {
        ExtensionFileFilter eff = (ExtensionFileFilter) ff;

        // #TODO: bio-formats release 4.2.2 contains a bug in the ExtensionFileFilter.accept(.)
        // method,
        //  therefore the extensions are matched manually. Substitute the for-loop with
        // accept()-method when
        //  using a new release
        String[] exts = eff.getExtensions();
        boolean extmatch = false;
        for (String ext : exts) {
          if (outfile.getName().endsWith(ext)) {
            extmatch = true;
            break;
          }
        }

        if (!extmatch) {
          outfile = new File(outfile.getAbsolutePath() + "." + eff.getExtension());
        }
      }

      // set initial directory of the file chooser for future call
      if (outfile.getParent() != null) {
        OpenDialog.setLastDirectory(outfile.getParent());
        OpenDialog.setDefaultDirectory(outfile.getParent());
      }

      // determine overwrite flag if file exists
      boolean overwrite = false;
      if (outfile.exists()) {
        int ret =
            JOptionPane.showConfirmDialog(
                null,
                "Do you want to overwrite existing file '" + outfile.getName() + "'?",
                "File exists",
                JOptionPane.YES_NO_OPTION);

        if (ret == JOptionPane.YES_OPTION) overwrite = true;
        else continue;
      }

      // create a MiToBo image writer instance
      ImageWriterMTB writer = null;

      try {
        if (this.img != null) {
          writer = new ImageWriterMTB(this.img, outfile.getAbsolutePath());
        } else {
          writer = new ImageWriterMTB(this.imp, outfile.getAbsolutePath());
        }
      } catch (ALDOperatorException e) {
        IJ.error("Image writer instantiation failed: " + e.getMessage());
      }

      if (writer != null) {

        // listener for status and progress bar update
        writer.addStatusListener(this);

        // configure and run the writer
        try {
          writer.setOverwrite(overwrite);

          if (this.compression != null) {
            writer.setCompression(this.compression);
          }
          if (this.fps > 0) {
            writer.setFps(this.fps);
          }
          if (this.quality != -1) {
            writer.setQuality(this.quality);
          }
          if (this.codec != -1) {
            writer.setCodec(this.codec);
          }

          writer.runOp(null);

        } catch (ALDOperatorException e) {
          IJ.error("Writing of file '" + outfile.getName() + "' failed: " + e.getMessage());
          e.printStackTrace();
        } catch (FormatException e) {
          IJ.error("Writing of file '" + outfile.getName() + "' failed: " + e.getMessage());
          e.printStackTrace();
        } catch (ALDProcessingDAGException e) {
          IJ.error("Writing of file '" + outfile.getName() + "' failed: " + e.getMessage());
          e.printStackTrace();
        }
      }

      return;
    }
  }
Exemplo n.º 22
0
  /** Descripción de Método */
  private void cmd_export() {
    log.config("");

    if (!m_isCanExport) {
      ADialog.error(m_WindowNo, this, "AccessCannotExport", getTitle());

      return;
    }

    //

    JFileChooser chooser = new JFileChooser();

    chooser.setDialogType(JFileChooser.SAVE_DIALOG);
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setDialogTitle(Msg.getMsg(m_ctx, "Export") + ": " + getTitle());

    //

    chooser.addChoosableFileFilter(new ExtensionFileFilter("ps", Msg.getMsg(m_ctx, "FilePS")));
    chooser.addChoosableFileFilter(new ExtensionFileFilter("xml", Msg.getMsg(m_ctx, "FileXML")));
    chooser.addChoosableFileFilter(new ExtensionFileFilter("pdf", Msg.getMsg(m_ctx, "FilePDF")));
    chooser.addChoosableFileFilter(new ExtensionFileFilter("html", Msg.getMsg(m_ctx, "FileHTML")));
    chooser.addChoosableFileFilter(new ExtensionFileFilter("txt", Msg.getMsg(m_ctx, "FileTXT")));
    chooser.addChoosableFileFilter(new ExtensionFileFilter("ssv", Msg.getMsg(m_ctx, "FileSSV")));
    chooser.addChoosableFileFilter(new ExtensionFileFilter("csv", Msg.getMsg(m_ctx, "FileCSV")));

    //

    if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) {
      return;
    }

    // Create File

    File outFile = ExtensionFileFilter.getFile(chooser.getSelectedFile(), chooser.getFileFilter());

    try {
      outFile.createNewFile();
    } catch (IOException e) {
      log.log(Level.SEVERE, "", e);
      ADialog.error(m_WindowNo, this, "FileCannotCreate", e.getLocalizedMessage());

      return;
    }

    String ext = outFile.getPath();

    // no extension

    if (ext.lastIndexOf(".") == -1) {
      ADialog.error(m_WindowNo, this, "FileInvalidExtension");

      return;
    }

    ext = ext.substring(ext.lastIndexOf(".") + 1).toLowerCase();
    log.config("File=" + outFile.getPath() + "; Type=" + ext);
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

    if (ext.equalsIgnoreCase("pdf")) {
      m_reportEngine.createPDF(outFile);
    } else if (ext.equals("ps")) {
      m_reportEngine.createPS(outFile);
    } else if (ext.equals("xml")) {
      m_reportEngine.createXML(outFile);
    } else if (ext.equals("csv")) {
      m_reportEngine.createCSV(outFile, ',', m_reportEngine.getPrintFormat().getLanguage());
    } else if (ext.equals("ssv")) {
      m_reportEngine.createCSV(outFile, ';', m_reportEngine.getPrintFormat().getLanguage());
    } else if (ext.equals("txt")) {
      m_reportEngine.createCSV(outFile, '\t', m_reportEngine.getPrintFormat().getLanguage());
    } else if (ext.equals("html") || ext.equals("htm")) {
      m_reportEngine.createHTML(outFile, false, m_reportEngine.getPrintFormat().getLanguage());
    } else {
      ADialog.error(m_WindowNo, this, "FileInvalidExtension");
    }

    cmd_drill(); // setCursor
  } // cmd_export
Exemplo n.º 23
0
  public File[] getFiles(
      boolean open,
      boolean multiple,
      String message,
      String file,
      final File directory,
      String... filter) {
    if (directory == null) {
      fileChooser = new JFileChooser(fileChooser.getCurrentDirectory());
    } else {
      fileChooser = new JFileChooser(directory);
    }
    if (file != null) {
      fileChooser.setSelectedFile(new File(directory, file));
    }
    fileChooser.setMultiSelectionEnabled(multiple);

    if (filter.length > 0) {
      for (int i = 0; i < filter.length; i += 2) {
        final String description = filter[i];
        final String suffix = filter[i + 1].toLowerCase();
        MyFileFilter fileFilter =
            new MyFileFilter() {

              @Override
              public boolean accept(File f) {
                if (f.isDirectory()) {
                  return true;
                }
                String name = f.getName().toLowerCase();
                return name.endsWith(suffix);
              }

              @Override
              public String getDescription() {
                return description;
              }
            };
        fileFilter.suffix = suffix;
        fileChooser.addChoosableFileFilter(fileFilter);
      }

      if (file != null) {
        int dot = file.lastIndexOf('.');
        if (dot >= 0) {
          String type = file.substring(dot + 1);
          for (FileFilter _filter : fileChooser.getChoosableFileFilters()) {
            if (_filter instanceof MyFileFilter) {
              if (((MyFileFilter) _filter).suffix.equals(type)) {
                fileChooser.setFileFilter(_filter);
                break;
              }
            }
          }
        }
      }
    }
    fileChooser.setDialogTitle(message);
    int ret;
    if (open) {
      ret = fileChooser.showOpenDialog(this);
    } else {
      ret = fileChooser.showSaveDialog(this);
    }
    if (ret == JFileChooser.APPROVE_OPTION) {
      if (multiple) {
        if (fileChooser.getSelectedFiles() == null || fileChooser.getSelectedFiles().length == 0) {
          return null;
        }
        return fileChooser.getSelectedFiles();
      }
      File selectedFile = fileChooser.getSelectedFile();
      if (!open) {
        FileFilter selectedFilter = fileChooser.getFileFilter();
        if (selectedFilter instanceof MyFileFilter) {
          String type = ((MyFileFilter) selectedFilter).suffix;
          selectedFile = UIUtilities.affixType(selectedFile, type);
        }
      }
      return new File[] {selectedFile};
    }
    return null;
  }
Exemplo n.º 24
0
    public void actionPerformed(ActionEvent e) {
      if (isDirectorySelected()) {
        File dir = getDirectory();
        if (dir != null) {
          try {
            // Strip trailing ".."
            dir = ShellFolder.getNormalizedFile(dir);
          } catch (IOException ex) {
            // Ok, use f as is
          }
          changeDirectory(dir);
          return;
        }
      }

      JFileChooser chooser = getFileChooser();

      String filename = getFileName();
      FileSystemView fs = chooser.getFileSystemView();
      File dir = chooser.getCurrentDirectory();

      if (filename != null) {
        // Remove whitespaces from end of filename
        int i = filename.length() - 1;

        while (i >= 0 && filename.charAt(i) <= ' ') {
          i--;
        }

        filename = filename.substring(0, i + 1);
      }

      if (filename == null || filename.length() == 0) {
        // no file selected, multiple selection off, therefore cancel the approve action
        resetGlobFilter();
        return;
      }

      File selectedFile = null;
      File[] selectedFiles = null;

      // Unix: Resolve '~' to user's home directory
      if (File.separatorChar == '/') {
        if (filename.startsWith("~/")) {
          filename = System.getProperty("user.home") + filename.substring(1);
        } else if (filename.equals("~")) {
          filename = System.getProperty("user.home");
        }
      }

      if (chooser.isMultiSelectionEnabled()
          && filename.length() > 1
          && filename.charAt(0) == '"'
          && filename.charAt(filename.length() - 1) == '"') {
        List<File> fList = new ArrayList<File>();

        String[] files = filename.substring(1, filename.length() - 1).split("\" \"");
        // Optimize searching files by names in "children" array
        Arrays.sort(files);

        File[] children = null;
        int childIndex = 0;

        for (String str : files) {
          File file = fs.createFileObject(str);
          if (!file.isAbsolute()) {
            if (children == null) {
              children = fs.getFiles(dir, false);
              Arrays.sort(children);
            }
            for (int k = 0; k < children.length; k++) {
              int l = (childIndex + k) % children.length;
              if (children[l].getName().equals(str)) {
                file = children[l];
                childIndex = l + 1;
                break;
              }
            }
          }
          fList.add(file);
        }

        if (!fList.isEmpty()) {
          selectedFiles = fList.toArray(new File[fList.size()]);
        }
        resetGlobFilter();
      } else {
        selectedFile = fs.createFileObject(filename);
        if (!selectedFile.isAbsolute()) {
          selectedFile = fs.getChild(dir, filename);
        }
        // check for wildcard pattern
        FileFilter currentFilter = chooser.getFileFilter();
        if (!selectedFile.exists() && isGlobPattern(filename)) {
          changeDirectory(selectedFile.getParentFile());
          if (globFilter == null) {
            globFilter = new GlobFilter();
          }
          try {
            globFilter.setPattern(selectedFile.getName());
            if (!(currentFilter instanceof GlobFilter)) {
              actualFileFilter = currentFilter;
            }
            chooser.setFileFilter(null);
            chooser.setFileFilter(globFilter);
            return;
          } catch (PatternSyntaxException pse) {
            // Not a valid glob pattern. Abandon filter.
          }
        }

        resetGlobFilter();

        // Check for directory change action
        boolean isDir = (selectedFile != null && selectedFile.isDirectory());
        boolean isTrav = (selectedFile != null && chooser.isTraversable(selectedFile));
        boolean isDirSelEnabled = chooser.isDirectorySelectionEnabled();
        boolean isFileSelEnabled = chooser.isFileSelectionEnabled();
        boolean isCtrl =
            (e != null
                && (e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0);

        if (isDir && isTrav && (isCtrl || !isDirSelEnabled)) {
          changeDirectory(selectedFile);
          return;
        } else if ((isDir || !isFileSelEnabled)
            && (!isDir || !isDirSelEnabled)
            && (!isDirSelEnabled || selectedFile.exists())) {
          selectedFile = null;
        }
      }

      if (selectedFiles != null || selectedFile != null) {
        if (selectedFiles != null || chooser.isMultiSelectionEnabled()) {
          if (selectedFiles == null) {
            selectedFiles = new File[] {selectedFile};
          }
          chooser.setSelectedFiles(selectedFiles);
          // Do it again. This is a fix for bug 4949273 to force the
          // selected value in case the ListSelectionModel clears it
          // for non-existing file names.
          chooser.setSelectedFiles(selectedFiles);
        } else {
          chooser.setSelectedFile(selectedFile);
        }
        chooser.approveSelection();
      } else {
        if (chooser.isMultiSelectionEnabled()) {
          chooser.setSelectedFiles(null);
        } else {
          chooser.setSelectedFile(null);
        }
        chooser.cancelSelection();
      }
    }
Exemplo n.º 25
0
  @Override
  void mergeTiffs() {
    JFileChooser jf = new JFileChooser();
    jf.setDialogTitle(bundle.getString("Select") + " Input Images");
    jf.setCurrentDirectory(imageFolder);
    jf.setMultiSelectionEnabled(true);
    FileFilter tiffFilter = new SimpleFilter("tif;tiff", "TIFF");
    FileFilter jpegFilter = new SimpleFilter("jpg;jpeg", "JPEG");
    FileFilter gifFilter = new SimpleFilter("gif", "GIF");
    FileFilter pngFilter = new SimpleFilter("png", "PNG");
    FileFilter bmpFilter = new SimpleFilter("bmp", "Bitmap");
    FileFilter allImageFilter =
        new SimpleFilter("tif;tiff;jpg;jpeg;gif;png;bmp", "All Image Files");

    jf.addChoosableFileFilter(tiffFilter);
    jf.addChoosableFileFilter(jpegFilter);
    jf.addChoosableFileFilter(gifFilter);
    jf.addChoosableFileFilter(pngFilter);
    jf.addChoosableFileFilter(bmpFilter);
    jf.addChoosableFileFilter(allImageFilter);

    if (selectedFilter != null) {
      jf.setFileFilter(selectedFilter);
    }

    jf.setAcceptAllFileFilterUsed(false);
    if (jf.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
      selectedFilter = jf.getFileFilter();
      final File[] inputs = jf.getSelectedFiles();
      imageFolder = jf.getCurrentDirectory();

      jf = new JFileChooser();
      jf.setDialogTitle(bundle.getString("Save") + " Multi-page TIFF Image");
      jf.setCurrentDirectory(imageFolder);
      jf.setFileFilter(tiffFilter);
      jf.setAcceptAllFileFilterUsed(false);
      if (jf.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        File selectedFile = jf.getSelectedFile();
        if (!(selectedFile.getName().endsWith(".tif")
            || selectedFile.getName().endsWith(".tiff"))) {
          selectedFile = new File(selectedFile.getParent(), selectedFile.getName() + ".tif");
        }

        final File outputTiff = selectedFile;
        if (outputTiff.exists()) {
          outputTiff.delete();
        }

        jLabelStatus.setText(bundle.getString("Merge_running..."));
        jProgressBar1.setIndeterminate(true);
        jProgressBar1.setString(bundle.getString("Merge_running..."));
        jProgressBar1.setVisible(true);
        getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        getGlassPane().setVisible(true);

        SwingWorker worker =
            new SwingWorker<File, Void>() {

              @Override
              protected File doInBackground() throws Exception {
                ImageIOHelper.mergeTiff(inputs, outputTiff);
                return outputTiff;
              }

              @Override
              protected void done() {
                jLabelStatus.setText(bundle.getString("Mergecompleted"));
                jProgressBar1.setIndeterminate(false);
                jProgressBar1.setString(bundle.getString("Mergecompleted"));

                try {
                  File result = get();
                  JOptionPane.showMessageDialog(
                      GuiWithTools.this,
                      bundle.getString("Mergecompleted")
                          + result.getName()
                          + bundle.getString("created"),
                      APP_NAME,
                      JOptionPane.INFORMATION_MESSAGE);
                } catch (InterruptedException ignore) {
                  ignore.printStackTrace();
                } catch (java.util.concurrent.ExecutionException e) {
                  String why = null;
                  Throwable cause = e.getCause();
                  if (cause != null) {
                    if (cause instanceof OutOfMemoryError) {
                      why = bundle.getString("OutOfMemoryError");
                    } else {
                      why = cause.getMessage();
                    }
                  } else {
                    why = e.getMessage();
                  }
                  e.printStackTrace();
                  JOptionPane.showMessageDialog(
                      GuiWithTools.this, why, APP_NAME, JOptionPane.ERROR_MESSAGE);
                } finally {
                  jProgressBar1.setVisible(false);
                  getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                  getGlassPane().setVisible(false);
                }
              }
            };

        worker.execute();
      }
    }
  }
Exemplo n.º 26
0
  /**
   * Handles the "Export" User action. Prompts the user for a file name and file type and calls the
   * appropriate utility methods to do the actual export.
   */
  public void export() {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileFilter(null);
    fileChooser.addChoosableFileFilter(SuffixFileFilter.HTML);
    fileChooser.addChoosableFileFilter(SuffixFileFilter.CSV);

    int retVal = fileChooser.showSaveDialog(this);
    if (retVal == JFileChooser.APPROVE_OPTION) {
      File selectedFile = fileChooser.getSelectedFile();
      selectedFile = ((SuffixFileFilter) fileChooser.getFileFilter()).makeAcceptable(selectedFile);
      if (selectedFile.exists()) {
        if (selectedFile.canWrite()) {
          int chosen =
              JOptionPane.showConfirmDialog(
                  this,
                  Messages.getString("Main.11"),
                  Messages.getString("Main.12"),
                  JOptionPane.YES_NO_OPTION,
                  JOptionPane.QUESTION_MESSAGE); // $NON-NLS-1$ //$NON-NLS-2$
          if (chosen == JOptionPane.NO_OPTION) {
            return;
          }
        } else {
          JOptionPane.showMessageDialog(
              this,
              Messages.getString("Main.13"),
              Messages.getString("Main.14"),
              JOptionPane.ERROR_MESSAGE); // $NON-NLS-1$ //$NON-NLS-2$
          return;
        }
      }
      PrintStream ps;
      try {
        ps = new PrintStream(new FileOutputStream(selectedFile));
        if ((fileChooser.getFileFilter() == SuffixFileFilter.HTML)) {
          String imageURL =
              selectedFile
                      .getAbsolutePath()
                      .substring(0, selectedFile.getAbsolutePath().length() - 4)
                  + "png";
          File imageFile = new File(imageURL);
          FileOutputStream fos = new FileOutputStream(imageFile);
          DriveTrainPNGWriter.writePNG(
              fos,
              driveTrainDrawing,
              driveTrainDrawing.getSize().width,
              driveTrainDrawing.getSize().height);
          fos.close();
          DriveTrainHTMLWriter.writeHTML(ps, new TableAdapter(model, style), imageFile.getName());
        } else {
          DriveTrainCSVWriter.writeCSV(ps, model);
        }
        ps.close();
      } catch (IOException e) {
        JOptionPane.showMessageDialog(
            this,
            Messages.format("Main.15", e.getLocalizedMessage()), // $NON-NLS-1$
            Messages.getString("Main.16"),
            JOptionPane.ERROR_MESSAGE); // $NON-NLS-1$
      }
    }
  }
Exemplo n.º 27
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);
    }
  }