ij.io.OpenDialog Java Examples

The following examples show how to use ij.io.OpenDialog. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BookmarkPanel.java    From 3Dscript with BSD 2-Clause "Simplified" License 6 votes vote down vote up
void loadBookmarks() {
	JFileChooser fc = new JFileChooser(OpenDialog.getLastDirectory());
	fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
	fc.setFileFilter(new FileFilter() {
		@Override
		public boolean accept(File f) {
			return f.isDirectory() || f.getName().toLowerCase().endsWith(".bookmarks.txt");
		}

		@Override
		public String getDescription() {
			return "Bookmark File";
		}
	});
	int s = fc.showOpenDialog(null);
	if(s != JFileChooser.APPROVE_OPTION)
		return;

	String path = fc.getSelectedFile().getAbsolutePath();
	loadBookmarks(path);
}
 
Example #2
Source File: BookmarkPanel.java    From 3Dscript with BSD 2-Clause "Simplified" License 6 votes vote down vote up
void saveBookmarks() {
	JFileChooser fc = new JFileChooser(OpenDialog.getLastDirectory());
	fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
	fc.setFileFilter(new FileFilter() {
		@Override
		public boolean accept(File f) {
			return f.isDirectory() || f.getName().toLowerCase().endsWith(".bookmarks.txt");
		}

		@Override
		public String getDescription() {
			return "Bookmark File";
		}
	});
	int s = fc.showSaveDialog(null);
	if(s == JFileChooser.APPROVE_OPTION) {
		String path = fc.getSelectedFile().getAbsolutePath();
		saveBookmarks(path);
	}
}
 
Example #3
Source File: Utils.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
/** Select a file from the file system, for saving purposes. Prompts for overwritting if the file exists, unless the ControlWindow.isGUIEnabled() returns false (i.e. there is no GUI). */
static public final File chooseFile(final String default_dir, final String name, final String extension) {
	try { return new TaskOnEDT<File>(new Callable<File>() { @Override
	public File call() {
	// using ImageJ's JFileChooser or internal FileDialog, according to user preferences.
	String name2 = null;
	if (null != name && null != extension) name2 = name + extension;
	else if (null != name) name2 = name;
	else if (null != extension) name2 = "untitled" + extension;
	if (null != default_dir) {
		OpenDialog.setDefaultDirectory(default_dir);
	}
	final SaveDialog sd = new SaveDialog("Save",
					OpenDialog.getDefaultDirectory(),
					name2,
					extension);

	final String filename = sd.getFileName();
	if (null == filename || filename.toLowerCase().startsWith("null")) return null;
	String dir = sd.getDirectory();
	if (IJ.isWindows()) dir = dir.replace('\\', '/');
	if (!dir.endsWith("/")) dir += "/";
	final File f = new File(dir + filename);
	if (f.exists() && ControlWindow.isGUIEnabled()) {
		final YesNoCancelDialog d = new YesNoCancelDialog(IJ.getInstance(), "Overwrite?", "File " + filename + " exists! Overwrite?");
		if (d.cancelPressed()) {
			return null;
		} else if (!d.yesPressed()) {
			return chooseFile(name, extension);
		}
		// else if yes pressed, overwrite.
	}
	return f;
	}}).get(); } catch (final Throwable t) { IJError.print(t); return null; }
}
 
Example #4
Source File: Loader.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
/** Ask for the user to provide a template XML file to extract a root TemplateThing. */
public TemplateThing askForXMLTemplate(final Project project) {
	// ask for an .xml file or a .dtd file
	//fd.setFilenameFilter(new XMLFileFilter(XMLFileFilter.BOTH));
	final OpenDialog od = new OpenDialog("Select XML Template",
					OpenDialog.getDefaultDirectory(),
					null);
	final String filename = od.getFileName();
	if (null == filename || filename.toLowerCase().startsWith("null")) return null;
	// if there is a path, read it out if possible
	String dir = od.getDirectory();
	if (null == dir) return null;
	if (IJ.isWindows()) dir = dir.replace('\\', '/');
	if (!dir.endsWith("/")) dir += "/";
	TemplateThing[] roots;
	try {
		roots = DTDParser.extractTemplate(dir + filename);
	} catch (final Exception e) {
		IJError.print(e);
		return null;
	}
	if (null == roots || roots.length < 1) return null;
	if (roots.length > 1) {
		Utils.showMessage("Found more than one root.\nUsing first root only.");
	}
	return roots[0];
}
 
Example #5
Source File: AmiraImporter.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
/** Returns the array of AreaList or null if the file dialog is canceled. The xo,yo is the pivot of reference. */
static public Collection<AreaList> importAmiraLabels(Layer first_layer, double xo, double yo, final String default_dir) {
	// open file
	OpenDialog od = new OpenDialog("Choose Amira Labels File", default_dir, "");
	String filename = od.getFileName();
	if (null == filename || 0 == filename.length()) return null;
	String dir = od.getDirectory();
	if (IJ.isWindows()) dir = dir.replace('\\', '/');
	if (!dir.endsWith("/")) dir += "/";
	String path =  dir + filename;
	AmiraMeshDecoder dec = new AmiraMeshDecoder();
	if (!dec.open(path)) {
		YesNoDialog yn = new YesNoDialog("Error", "File was not an Amira labels file.\nChoose another one?");
		if (yn.yesPressed()) return importAmiraLabels(first_layer, xo, yo, default_dir);
		return null;
	}
	ImagePlus imp = null;
	if (dec.isTable()) {
		Utils.showMessage("Select the other file (the labels)!");
		return null;
	} else {
		FileInfo fi = new FileInfo();
		fi.fileName = filename;
		fi.directory = dir;
		imp = new ImagePlus("Amira", dec.getStack());
		dec.parameters.setParameters(imp);
	}
	return extractAmiraLabels(imp, dec.parameters, first_layer, xo, yo);
}
 
Example #6
Source File: AnimationEditor.java    From 3Dscript with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private File openWithDialog(final File defaultDir) {
	String defaultdir = defaultDir == null ? "" : defaultDir.getAbsolutePath();
	OpenDialog od = new OpenDialog("Open", defaultdir, "");
	String path = od.getPath();
	return path == null ? null : new File(path);
}
 
Example #7
Source File: Commander.java    From Scripts with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Executes console commands. Outputs one of the following exit status:
 * <p>
 * "0": Executed a a self-contained command that need no follow-up. null:
 * Failed to retrieve a path. non-null string: A successfully retrieved path
 *
 * @see #interpretCommand
 */
String execCommand(final String cmd) {

	// Case "0": Self-contained commands that need no follow-up
	String exitStatus = String.valueOf(0);
	if (cmd.startsWith("quit")) {
		quit();
		return exitStatus;
	} else if (cmd.startsWith("help")) {
		new ij.gui.HTMLDialog("Commander Help", helpMessage(), false);
		return exitStatus;
	} else if (cmd.startsWith("ls")) {
		printList();
		return exitStatus;
	} else if (cmd.equals("options")) {
		showOptionsDialog();
		return exitStatus;
	} else if (cmd.startsWith("refresh")) {
		freezeStatusBar = false;
		return exitStatus;
	} else if (cmd.startsWith("..")) {
		selectParentDirectory(path);
		return exitStatus;
	} else if (cmd.equals("bookmark")) {
		addBookmark();
		return exitStatus;
	} else if (cmd.equals("cd")) {
		cdToDirectory(path);
		return exitStatus;
	} else if (cmd.startsWith("info")) {
		showInfo();
		return exitStatus;
	}

	// Remaining cases: Commands that only retrieve paths
	exitStatus = null;
	if (cmd.startsWith("goto")) {
		exitStatus = IJ.getDirectory("Choose new directory");
	} else if (cmd.startsWith("~")) {
		exitStatus = IJ.getDirectory("home");
	} else if (cmd.startsWith("imp")) {
		exitStatus = IJ.getDirectory("image");
	} else if (cmd.equals("luts")) {
		exitStatus = IJ.getDirectory(cmd);
	} else if (cmd.equals("macros")) {
		exitStatus = IJ.getDirectory(cmd);
	} else if (cmd.equals("plugins")) {
		exitStatus = IJ.getDirectory(cmd);
	} else if (cmd.startsWith("pwd")) {
		exitStatus = OpenDialog.getDefaultDirectory();
	} else if (cmd.equals("ij")) {
		exitStatus = IJ.getDirectory("imagej");
	} else if (cmd.startsWith("tmp")) {
		exitStatus = IJ.getDirectory("temp");
	} else if (cmd.equals("myr")) {
		exitStatus = Utils.getMyRoutinesDir();
	} else if (cmd.equals("lib")) {
		exitStatus = Utils.getLibDir();
	} else if (cmd.equals("samples")) {
		exitStatus = IJ.getDirectory("imagej") + cmd;
	} else if (cmd.equals("scripts")) {
		exitStatus = IJ.getDirectory("imagej") + cmd;
	}

	if (exitStatus != null && exitStatus.isEmpty())
		exitStatus = null;

	return exitStatus;

}
 
Example #8
Source File: Utils.java    From Scripts with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Opens a tab or comma delimited text file.
 *
 * @param path
 *            The absolute pathname string of the file. A file open dialog
 *            is displayed if path is {@code null} or an empty string.
 * @param title
 *            The title of the window in which data is displayed. The
 *            filename is used if title is null or an empty string. To avoid
 *            windows with duplicated titles, title is made unique by
 *            {@link WindowManager} .
 * @param listener
 *            The {@link WindowListener} to be added to the window
 *            containing data if retrieval was successful. It is ignored
 *            when {@code null}.
 * @throws IOException
 *             if file could not be opened
 * @return A reference to the opened {link ResultsTable} or {@code null} if
 *         table was empty.
 *
 * @see #getTable()
 * @see ij.io.Opener#openTable(String)
 */
public static ResultsTable openAndDisplayTable(final String path, final String title, final WindowListener listener)
		throws IOException {
	ResultsTable rt = null;
	rt = ResultsTable.open(path);
	if (rt == null || rt.getCounter() == 0) // nothing to be displayed
		return null;
	rt.showRowNumbers(false);
	String rtTitle = (title != null && !title.isEmpty()) ? title : OpenDialog.getLastName();
	rtTitle = WindowManager.makeUniqueName(rtTitle);
	rt.show(rtTitle);
	final TextWindow rtWindow = (TextWindow) WindowManager.getFrame(rtTitle);
	if (rtWindow != null && listener != null)
		rtWindow.addWindowListener(listener);
	return rt;
}
 
Example #9
Source File: Render.java    From TrakEM2 with GNU General Public License v3.0 4 votes vote down vote up
static public void exportSVG(ProjectThing thing, double z_scale) {
	StringBuffer data = new StringBuffer();
	data.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n")
	    .append("<svg\n")
	    .append("\txmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n")
	    .append("\txmlns:cc=\"http://web.resource.org/cc/\"\n")
	    .append("\txmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n")
	    .append("\txmlns:svg=\"http://www.w3.org/2000/svg\"\n")
	    .append("\txmlns=\"http://www.w3.org/2000/svg\"\n")
	    //.append("\twidth=\"1500\"\n")
	    //.append("\theight=\"1000\"\n")
	    .append("\tid=\"").append(thing.getProject().toString()).append("\">\n")
	;
	// traverse the tree at node 'thing'
	thing.exportSVG(data, z_scale, "\t");

	data.append("</svg>");

	// save the file
	final SaveDialog sd = new SaveDialog("Save .svg", OpenDialog.getDefaultDirectory(), "svg");
	String dir = sd.getDirectory();
	if (null == dir) return;
	if (IJ.isWindows()) dir = dir.replace('\\', '/');
	if (!dir.endsWith("/")) dir += "/";
	String file_name = sd.getFileName();
	String file_path = dir + file_name;
	File f = new File(file_path);
	if (f.exists()) {
		YesNoCancelDialog d = new YesNoCancelDialog(IJ.getInstance(), "Overwrite?", "File " + file_name + " exists! Overwrite?");
		if (!d.yesPressed()) {
			return;
		}
	}
	String contents = data.toString();
	try {
		DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f), data.length()));
		dos.writeBytes(contents);
		dos.flush();
	} catch (Exception e) {
		IJError.print(e);
		Utils.log("ERROR: Most likely did NOT save your file.");
	}
}
 
Example #10
Source File: Loader.java    From TrakEM2 with GNU General Public License v3.0 4 votes vote down vote up
/** A dialog to open a stack, making sure there is enough memory for it. */
synchronized public ImagePlus openStack() {
	final OpenDialog od = new OpenDialog("Select stack", OpenDialog.getDefaultDirectory(), null);
	final String file_name = od.getFileName();
	if (null == file_name || file_name.toLowerCase().startsWith("null")) return null;
	String dir = od.getDirectory().replace('\\', '/');
	if (!dir.endsWith("/")) dir += "/";

	final File f = new File(dir + file_name);
	if (!f.exists()) {
		Utils.showMessage("File " + dir + file_name  + " does not exist.");
		return null;
	}
	// avoid opening trakem2 projects
	if (file_name.toLowerCase().endsWith(".xml")) {
		Utils.showMessage("Cannot import " + file_name + " as a stack.");
		return null;
	}
	// estimate file size: assumes an uncompressed tif, or a zipped tif with an average compression ratio of 2.5
	long size = f.length() / 1024; // in megabytes
	if (file_name.length() -4 == file_name.toLowerCase().lastIndexOf(".zip")) {
		size = (long)(size * 2.5); // 2.5 is a reasonable compression ratio estimate based on my experience
	}
	releaseToFit(size);
	ImagePlus imp_stack = null;
	try {
		IJ.redirectErrorMessages();
		imp_stack = openImagePlus(f.getCanonicalPath());
	} catch (final Exception e) {
		IJError.print(e);
		return null;
	}
	if (null == imp_stack) {
		Utils.showMessage("Can't open the stack.");
		return null;
	} else if (1 == imp_stack.getStackSize()) {
		Utils.showMessage("Not a stack!");
		return null;
	}
	return imp_stack; // the open... command
}
 
Example #11
Source File: Loader.java    From TrakEM2 with GNU General Public License v3.0 4 votes vote down vote up
/** If base_x or base_y are Double.MAX_VALUE, then those values are asked for in a GenericDialog. */
public Bureaucrat importLabelsAsAreaLists(final Layer first_layer, final String path_, final double base_x_, final double base_y_, final float alpha_, final boolean add_background_) {
	final Worker worker = new Worker("Import labels as arealists") {
		@Override
           public void run() {
			startedWorking();
			try {
				String path = path_;
				if (null == path) {
					final OpenDialog od = new OpenDialog("Select stack", "");
					final String name = od.getFileName();
					if (null == name || 0 == name.length()) {
						return;
					}
					String dir = od.getDirectory().replace('\\', '/');
					if (!dir.endsWith("/")) dir += "/";
					path = dir + name;
				}
				if (path.toLowerCase().endsWith(".xml")) {
					Utils.log("Avoided opening a TrakEM2 project.");
					return;
				}
				double base_x = base_x_;
				double base_y = base_y_;
				float alpha = alpha_;
				boolean add_background = add_background_;
				Layer layer = first_layer;
				if (Double.MAX_VALUE == base_x || Double.MAX_VALUE == base_y || alpha < 0 || alpha > 1) {
					final GenericDialog gd = new GenericDialog("Base x, y");
					Utils.addLayerChoice("First layer:", first_layer, gd);
					gd.addNumericField("Base_X:", 0, 0);
					gd.addNumericField("Base_Y:", 0, 0);
					gd.addSlider("Alpha:", 0, 100, 40);
					gd.addCheckbox("Add background (zero)", false);
					gd.showDialog();
					if (gd.wasCanceled()) {
						return;
					}
					layer = first_layer.getParent().getLayer(gd.getNextChoiceIndex());
					base_x = gd.getNextNumber();
					base_y = gd.getNextNumber();
					if (Double.isNaN(base_x) || Double.isNaN(base_y)) {
						Utils.log("Base x or y is NaN!");
						return;
					}
					alpha = (float)(gd.getNextNumber() / 100);
					add_background = gd.getNextBoolean();
				}
				releaseToFit(new File(path).length() * 3);
				final ImagePlus imp;
				if (path.toLowerCase().endsWith(".am")) {
					final AmiraMeshDecoder decoder = new AmiraMeshDecoder();
					if (decoder.open(path)) imp = new ImagePlus(path, decoder.getStack());
					else imp = null;
				} else {
					imp = openImagePlus(path);
				}
				if (null == imp) {
					Utils.log("Could not open image at " + path);
					return;
				}
				final Map<Float,AreaList> alis = AmiraImporter.extractAreaLists(imp, layer, base_x, base_y, alpha, add_background);
				if (!hasQuitted() && alis.size() > 0) {
					layer.getProject().getProjectTree().insertSegmentations(alis.values());
				}
			} catch (final Exception e) {
				IJError.print(e);
			} finally {
				finishedWorking();
			}
		}
	};
	return Bureaucrat.createAndStart(worker, first_layer.getProject());
}
 
Example #12
Source File: Loader.java    From TrakEM2 with GNU General Public License v3.0 4 votes vote down vote up
/** Import a new image at the given coordinates; does not puts it into any layer, unless it's a stack -in which case importStack is called with the current front layer of the given project as target. If a path is not provided it will be asked for.*/
public Patch importImage(final Project project, final double x, final double y, String path, final boolean synch_mipmap_generation) {
	if (null == path) {
		final OpenDialog od = new OpenDialog("Import image", "");
		final String name = od.getFileName();
		if (null == name || 0 == name.length()) return null;
		String dir = od.getDirectory().replace('\\', '/');
		if (!dir.endsWith("/")) dir += "/";
		path = dir + name;
	} else {
		path = path.replace('\\', '/');
	}
	// avoid opening trakem2 projects
	if (path.toLowerCase().endsWith(".xml")) {
		Utils.showMessage("Cannot import " + path + " as a stack.");
		return null;
	}
	releaseToFit(new File(path).length() * 3);
	IJ.redirectErrorMessages();
	final ImagePlus imp = openImagePlus(path);
	if (null == imp) return null;
	if (imp.getNSlices() > 1) {
		// a stack!
		final Layer layer = Display.getFrontLayer(project);
		if (null == layer) return null;
		importStack(layer, x, y, imp, true, path, true);
		return null;
	}
	if (0 == imp.getWidth() || 0 == imp.getHeight()) {
		Utils.showMessage("Can't import image of zero width or height.");
		flush(imp);
		return null;
	}
	final Patch p = new Patch(project, imp.getTitle(), x, y, imp);
	addedPatchFrom(path, p);
	last_opened_path = path; // WARNING may be altered concurrently
	if (isMipMapsRegenerationEnabled()) {
		if (synch_mipmap_generation) {
			try {
				regenerateMipMaps(p).get(); // wait
			} catch (final Exception e) {
				IJError.print(e);
			}
		} else regenerateMipMaps(p); // queue for regeneration
	}
	return p;
}