Java Examples for java.awt.FileDialog
The following java examples will help you to understand the usage of java.awt.FileDialog. These source code samples are taken from different open source projects.
Example 1
| Project: javamoney-examples-master File: FileDialogHelper.java View source code |
/**
* This method prompts a user with a file dialog and returns the selected
* file, or null if the dialog was canceled.
*
* @return The selected file.
*/
public static File showOpenDialog() {
FileDialog chooser = new FileDialog(getFrame(), "", LOAD);
File file = null;
String fileName = null;
chooser.setDirectory(getLastSelectedDirectory().toString());
chooser.setVisible(true);
fileName = chooser.getFile();
if (fileName != null) {
file = new File(chooser.getDirectory() + separator + fileName);
// Save the last selected file.
setLastSelectedDirectory(file.getParentFile());
}
chooser.dispose();
return file;
}Example 2
| Project: PIPE-master File: ReachabilityGraph.java View source code |
/**
* Main method for running this externally without PIPE
*
* @param args command line arguments
*/
public static void main(String[] args) {
JFrame frame = new JFrame("ReachabilityGraph");
FileDialog selector = new FileDialog(frame, "Select petri net", FileDialog.LOAD);
frame.setContentPane(new ReachabilityGraph(selector).panel1);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}Example 3
| Project: yoshikoder-master File: YKReportDialog.java View source code |
protected void handleSave() {
// throw up export dialog
if (exportDialog == null)
exportDialog = new ExportDialog(this, new String[] { ExportUtil.HTML_FORMAT, ExportUtil.EXCEL_FORMAT });
exportDialog.show();
String format = exportDialog.getChosenFormat();
if (format == null)
return;
if (format == ExportUtil.HTML_FORMAT) {
if (htmlExporter == null)
htmlExporter = DialogUtil.makeFileDialog(yoshikoder, "Export as HTML", FileDialog.SAVE, // TODO loc
DialogUtil.htmlFilenameFilter);
htmlExporter.show();
String f = htmlExporter.getFile();
if (f == null)
return;
final File file = new File(htmlExporter.getDirectory(), f);
worker = new TaskWorker(this) {
protected void doWork() throws Exception {
report.saveAsHtml(FileUtil.suffix(file, "html", "htm"));
}
protected void onError() {
// TODO loc
DialogUtil.yelp(YKReportDialog.this, "Could not save as HTML", e);
}
};
worker.start();
} else {
if (excelExporter == null)
excelExporter = DialogUtil.makeFileDialog(yoshikoder, "Export as Excel", FileDialog.SAVE, // TODO loc
DialogUtil.xlsFilenameFilter);
excelExporter.show();
String f = excelExporter.getFile();
if (f == null)
return;
final File file = new File(excelExporter.getDirectory(), f);
worker = new TaskWorker(this) {
protected void doWork() throws Exception {
report.saveAsExcel(FileUtil.suffix(file, "xls"));
}
protected void onError() {
// TODO loc
DialogUtil.yelp(YKReportDialog.this, "Could not save as Excel", e);
}
};
worker.start();
}
}Example 4
| Project: josm-master File: NativeFileChooser.java View source code |
@Override
public void setFileSelectionMode(int selectionMode) {
// CHECKSTYLE.OFF: LineLength
// TODO implement this after Oracle fixes JDK-6192906 / JDK-6699863 / JDK-6927978 / JDK-7125172:
// https://bugs.openjdk.java.net/browse/JDK-6192906 : Add more features to java.awt.FileDialog
// https://bugs.openjdk.java.net/browse/JDK-6699863 : awt filedialog cannot select directories
// https://bugs.openjdk.java.net/browse/JDK-6927978 : Directory Selection standard dialog support
// https://bugs.openjdk.java.net/browse/JDK-7125172 : FileDialog objects don't allow directory AND files selection simultaneously
// There is however a basic support for directory selection on OS X, with Java >= 7u40:
// http://stackoverflow.com/questions/1224714/how-can-i-make-a-java-filedialog-accept-directories-as-its-filetype-in-os-x/1224744#1224744
// https://bugs.openjdk.java.net/browse/JDK-7161437 : [macosx] awt.FileDialog doesn't respond appropriately for mac when selecting folders
// CHECKSTYLE.ON: LineLength
this.selectionMode = selectionMode;
}Example 5
| Project: figtree-master File: TreeViewerPanel.java View source code |
public static void main(String[] args) {
JFrame frame = new JFrame("TreeViewer Test");
TreeViewer treeViewer = new DefaultTreeViewer(frame);
ControlPalette controlPalette = new BasicControlPalette(200, BasicControlPalette.DisplayMode.ONLY_ONE_OPEN);
frame.getContentPane().add(new TreeViewerPanel(frame, treeViewer, controlPalette), BorderLayout.CENTER);
try {
File inputFile = null;
if (args.length > 0) {
inputFile = new File(args[0]);
}
if (inputFile == null) {
// No input file name was given so throw up a dialog box...
java.awt.FileDialog chooser = new java.awt.FileDialog(frame, "Select NEXUS Tree File", java.awt.FileDialog.LOAD);
chooser.setVisible(true);
inputFile = new java.io.File(chooser.getDirectory(), chooser.getFile());
chooser.dispose();
}
if (inputFile == null) {
throw new RuntimeException("No file specified");
}
// TreeImporter importer = new NewickImporter(new FileReader(inputFile));
Reader reader = new BufferedReader(new FileReader(inputFile));
TreeImporter importer = new NexusImporter(reader);
java.util.List<Tree> trees = importer.importTrees();
reader.close();
treeViewer.setTrees(trees);
} catch (Exception ie) {
ie.printStackTrace();
System.exit(1);
}
frame.setSize(640, 480);
frame.setVisible(true);
}Example 6
| Project: beast-mcmc-master File: Utils.java View source code |
public static File getLoadFile(String message) {
// No file name in the arguments so throw up a dialog box...
java.awt.Frame frame = new java.awt.Frame();
java.awt.FileDialog chooser = new java.awt.FileDialog(frame, message, java.awt.FileDialog.LOAD);
// chooser.show();
chooser.setVisible(true);
if (chooser.getFile() == null)
return null;
java.io.File file = new java.io.File(chooser.getDirectory(), chooser.getFile());
chooser.dispose();
frame.dispose();
return file;
}Example 7
| Project: ieo-beast-master File: Utils.java View source code |
public static File getLoadFile(String message) {
// No file name in the arguments so throw up a dialog box...
java.awt.Frame frame = new java.awt.Frame();
java.awt.FileDialog chooser = new java.awt.FileDialog(frame, message, java.awt.FileDialog.LOAD);
// chooser.show();
chooser.setVisible(true);
if (chooser.getFile() == null)
return null;
java.io.File file = new java.io.File(chooser.getDirectory(), chooser.getFile());
chooser.dispose();
frame.dispose();
return file;
}Example 8
| Project: DensiTree-master File: Util.java View source code |
public static File[] getFile(String message, boolean bLoadNotSave, File defaultFileOrDir, boolean bAllowMultipleSelection, String description, final String... extensions) {
if (isMac()) {
java.awt.Frame frame = new java.awt.Frame();
java.awt.FileDialog chooser = new java.awt.FileDialog(frame, message, (bLoadNotSave ? java.awt.FileDialog.LOAD : java.awt.FileDialog.SAVE));
if (defaultFileOrDir != null) {
if (defaultFileOrDir.isDirectory()) {
chooser.setDirectory(defaultFileOrDir.getAbsolutePath());
} else {
chooser.setDirectory(defaultFileOrDir.getParentFile().getAbsolutePath());
chooser.setFile(defaultFileOrDir.getName());
}
}
if (description != null) {
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
for (int i = 0; i < extensions.length; i++) {
if (name.toLowerCase().endsWith(extensions[i].toLowerCase())) {
return true;
}
}
return false;
}
};
chooser.setFilenameFilter(filter);
}
//chooser.setMultipleMode(bAllowMultipleSelection);
chooser.setVisible(true);
if (chooser.getFile() == null)
return null;
//if (bAllowMultipleSelection) {
// return chooser.getFiles();
//}
File file = new java.io.File(chooser.getDirectory(), chooser.getFile());
chooser.dispose();
frame.dispose();
return new File[] { file };
} else {
// No file name in the arguments so throw up a dialog box...
java.awt.Frame frame = new java.awt.Frame();
frame.setTitle(message);
final JFileChooser chooser = new JFileChooser(defaultFileOrDir);
chooser.setMultiSelectionEnabled(bAllowMultipleSelection);
if (description != null) {
FileNameExtensionFilter filter = new FileNameExtensionFilter(description, extensions);
chooser.setFileFilter(filter);
}
if (bLoadNotSave) {
if (chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
frame.dispose();
if (bAllowMultipleSelection) {
return chooser.getSelectedFiles();
} else {
if (chooser.getSelectedFile() == null) {
return null;
}
return new File[] { chooser.getSelectedFile() };
}
}
} else {
if (chooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
frame.dispose();
if (bAllowMultipleSelection) {
return chooser.getSelectedFiles();
} else {
if (chooser.getSelectedFile() == null) {
return null;
}
return new File[] { chooser.getSelectedFile() };
}
}
}
}
return null;
}Example 9
| Project: Desktop-master File: FileDialogs.java View source code |
public static String getNewFileForMac(JFrame owner, File directory, String extensions, int dialogType, boolean updateWorkingDirectory, boolean dirOnly, FilenameFilter filter) {
java.awt.FileDialog fc = new java.awt.FileDialog(owner);
// fc.setFilenameFilter(filter);
if (directory != null) {
fc.setDirectory(directory.getParent());
}
if (dialogType == JFileChooser.OPEN_DIALOG) {
fc.setMode(java.awt.FileDialog.LOAD);
} else {
fc.setMode(java.awt.FileDialog.SAVE);
}
// fc.show(); -> deprecated since 1.5
fc.setVisible(true);
if (fc.getFile() != null) {
Globals.prefs.put("workingDirectory", fc.getDirectory() + fc.getFile());
return fc.getDirectory() + fc.getFile();
} else {
return null;
}
}Example 10
| Project: Docear-master File: FileDialogs.java View source code |
public static String getNewFileForMac(JFrame owner, File directory, String extensions, int dialogType, boolean updateWorkingDirectory, boolean dirOnly, FilenameFilter filter) {
java.awt.FileDialog fc = new java.awt.FileDialog(owner);
// fc.setFilenameFilter(filter);
if (directory != null) {
fc.setDirectory(directory.getParent());
}
if (dialogType == JFileChooser.OPEN_DIALOG) {
fc.setMode(java.awt.FileDialog.LOAD);
} else {
fc.setMode(java.awt.FileDialog.SAVE);
}
// fc.show(); -> deprecated since 1.5
fc.setVisible(true);
if (fc.getFile() != null) {
Globals.prefs.put("workingDirectory", fc.getDirectory() + fc.getFile());
return fc.getDirectory() + fc.getFile();
} else {
return null;
}
}Example 11
| Project: glitcherator-master File: GlitchActionListener.java View source code |
@Override
public void actionPerformed(ActionEvent e) {
GlitchPanel gp = (GlitchPanel) App.getAppComponents().get("Glitchpanel");
if (e.getActionCommand() == "save") {
String file = "img" + gp.getGlitch().getCtime() + ".jpg";
FileDialog fd = new FileDialog(App.frame, null, FileDialog.SAVE);
fd.setTitle("Save Glitched file...");
fd.setAlwaysOnTop(true);
fd.setFile(file);
fd.setVisible(true);
String filename = fd.getDirectory() + fd.getFile();
gp.getGlitch().export(filename);
}
if (e.getActionCommand() == "refresh") {
gp.getGlitch().refresh();
App.frame.repaint();
}
if (e.getActionCommand() == "open") {
FileDialog fd = new FileDialog(App.frame, null, FileDialog.LOAD);
Preferences prefs = Preferences.userNodeForPackage(glitcherator.App.class);
fd.setDirectory(prefs.get(GlitchPrefsFrame.SAVE_PATH_KEY, GlitchPrefsFrame.SAVE_PATH_VAL));
fd.setFilenameFilter(new FilenameFilter() {
public boolean accept(File dir, String name) {
// only jpeg for now
return (name.endsWith(".jpg"));
}
});
fd.setVisible(true);
String filename = fd.getDirectory() + fd.getFile();
gp.loadNewGlitch(filename);
}
if (e.getActionCommand() == "How") {
// cache panel
if (howToDialog == null) {
howToDialog = new GlitchHowToDialog();
}
howToDialog.setVisible(true);
}
if (e.getActionCommand() == "license") {
// cache panel
if (licenseDialog == null) {
licenseDialog = new GlitchLicenseDialog();
}
licenseDialog.setVisible(true);
}
}Example 12
| Project: jabref-2.9.2-master File: FileDialogs.java View source code |
public static String getNewFileForMac(JFrame owner, File directory, String extensions, int dialogType, boolean updateWorkingDirectory, boolean dirOnly, FilenameFilter filter) {
java.awt.FileDialog fc = new java.awt.FileDialog(owner);
// fc.setFilenameFilter(filter);
if (directory != null) {
fc.setDirectory(directory.getParent());
}
if (dialogType == JFileChooser.OPEN_DIALOG) {
fc.setMode(java.awt.FileDialog.LOAD);
} else {
fc.setMode(java.awt.FileDialog.SAVE);
}
// fc.show(); -> deprecated since 1.5
fc.setVisible(true);
if (fc.getFile() != null) {
Globals.prefs.put("workingDirectory", fc.getDirectory() + fc.getFile());
return fc.getDirectory() + fc.getFile();
} else {
return null;
}
}Example 13
| Project: jkappa-master File: PromptDialogs.java View source code |
private final File showFileDialog(String title, int mode, FilenameFilter filter, String filename) {
if (fileDialog == null)
fileDialog = new FileDialog(frame);
fileDialog.setTitle(title);
fileDialog.setMode(mode);
fileDialog.setFilenameFilter(filter);
if (filename != null)
fileDialog.setFile(filename);
fileDialog.setVisible(true);
if (fileDialog.getFile() == null)
return null;
else
return new File(fileDialog.getDirectory(), fileDialog.getFile());
}Example 14
| Project: LGA-master File: AWTOpenDialog.java View source code |
void open(String title, String path, String fileName) {
dialog = new FileDialog((Frame) LSystem.getSystemHandler().getWindow(), title);
if (path != null) {
dialog.setDirectory(path);
}
if (fileName != null) {
dialog.setFile(fileName);
}
fileName = dialog.getFile();
if (fileName == null) {
if (LSystem.isMacOS()) {
System.setProperty("apple.awt.fileDialogForDirectories", "false");
}
} else {
dirName = dialog.getDirectory();
}
}Example 15
| Project: LGame-master File: AWTOpenDialog.java View source code |
void open(String title, String path, String fileName) {
dialog = new FileDialog((Frame) LSystem.getSystemHandler().getWindow(), title);
if (path != null) {
dialog.setDirectory(path);
}
if (fileName != null) {
dialog.setFile(fileName);
}
fileName = dialog.getFile();
if (fileName == null) {
if (LSystem.isMacOS()) {
System.setProperty("apple.awt.fileDialogForDirectories", "false");
}
} else {
dirName = dialog.getDirectory();
}
}Example 16
| Project: montagnesdor-master File: TestGeneration.java View source code |
public static void main(String[] args) {
// Set the platform L&F.
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
// Load
FileDialog dialog = new FileDialog(new Frame(), "Open", FileDialog.LOAD);
dialog.setFile("*.odt");
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
String file = dialog.getFile();
if (file != null) {
if (dialog.getDirectory() != null) {
file = dialog.getDirectory() + System.getProperty("file.separator") + file;
}
try {
File templateFile = new File(file);
File outFile = new File("target/template/out2.odt");
RhinoFileTemplate template = new RhinoFileTemplate(templateFile);
template.setField("title", "title");
template.setField("toto", "toto");
template.setField("courseDate", "courseDate");
final List<Map<String, String>> infos = new ArrayList<Map<String, String>>();
infos.add(createMap("January", "-12"));
infos.add(createMap("February", "-8"));
infos.add(createMap("March", "-5"));
template.setField("infos", infos);
template.setField("months", infos);
template.hideParagraph("p1");
// Save to file.
outFile = template.saveAs(outFile);
// Open the document with OpenOffice.org !
OOUtils.open(outFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}Example 17
| Project: org.openscada.external-master File: TestGeneration.java View source code |
public static void main(String[] args) {
// Set the platform L&F.
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
// Load
FileDialog dialog = new FileDialog(new Frame(), "Open", FileDialog.LOAD);
dialog.setFile("*.odt");
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
String file = dialog.getFile();
if (file != null) {
if (dialog.getDirectory() != null) {
file = dialog.getDirectory() + System.getProperty("file.separator") + file;
}
try {
File templateFile = new File(file);
File outFile = new File("out2.odt");
RhinoFileTemplate template = new RhinoFileTemplate(templateFile);
template.setField("title", "title");
template.setField("toto", "toto");
template.setField("courseDate", "courseDate");
final List<Map<String, String>> infos = new ArrayList<Map<String, String>>();
infos.add(createMap("January", "-12"));
infos.add(createMap("February", "-8"));
infos.add(createMap("March", "-5"));
template.setField("infos", infos);
template.setField("months", infos);
template.hideParagraph("p1");
// Save to file.
outFile = template.saveAs(outFile);
// Open the document with OpenOffice.org !
OOUtils.open(outFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}Example 18
| Project: TemporalSearch-master File: TextConsole.java View source code |
public String rChooseFile(Rengine re, int newFile) {
FileDialog fd = new FileDialog(new Frame(), (newFile == 0) ? "Select a file" : "Select a new file", (newFile == 0) ? FileDialog.LOAD : FileDialog.SAVE);
fd.show();
String res = null;
if (fd.getDirectory() != null)
res = fd.getDirectory();
if (fd.getFile() != null)
res = (res == null) ? fd.getFile() : (res + fd.getFile());
return res;
}Example 19
| Project: wombat-ide-master File: ImageAPI.java View source code |
/**
* Show a dialog to allow the user to choose an image, then read it into a byte stream.
* @param dir The directory to read from.
* @return A stream of encoded data. The first two values are rows then columns, then the sequence is [r,g,b,a] across rows then down.
* @throws IOException If we cannot read the file.
*/
public static ImageData readImage() throws IOException {
FileDialog fc = new FileDialog((java.awt.Frame) null, "read-image", FileDialog.LOAD);
fc.setVisible(true);
if (fc.getFile() == null)
throw new IllegalArgumentException("Error in read-image: no image chosen.");
File file = new File(fc.getDirectory(), fc.getFile());
return readImage(null, file.getCanonicalPath());
}Example 20
| Project: Triana-master File: GsmEncoder.java View source code |
private void openMenuItem_ActionPerformed(java.awt.event.ActionEvent event) {
try {
int defMode = openFileDialog1.getMode();
String defTitle = openFileDialog1.getTitle();
String defDirectory = openFileDialog1.getDirectory();
String defFile = openFileDialog1.getFile();
openFileDialog1 = new java.awt.FileDialog(this, defTitle, defMode);
openFileDialog1.setDirectory(defDirectory);
openFileDialog1.setFile(defFile);
openFileDialog1.setVisible(true);
setLoadFileName();
} catch (Exception e) {
}
}Example 21
| Project: windowtester-master File: FileDialogRecorder.java View source code |
/** Override the default window parsing to consume everything between
dialog open and close.
*/
protected boolean parseWindowEvent(AWTEvent event) {
boolean consumed = true;
if (event.getSource() instanceof FileDialog) {
if (isOpen(event)) {
dialog = (FileDialog) event.getSource();
originalFile = dialog.getFile();
originalDir = dialog.getDirectory();
}
// listener is finished.
if (event instanceof FileDialogTerminator)
setFinished(true);
else if (event.getSource() == dialog && isClose(event)) {
AWTEvent terminator = new FileDialogTerminator(dialog, event.getID());
dialog.getToolkit().getSystemEventQueue().postEvent(terminator);
}
}
return consumed;
}Example 22
| Project: daap-master File: ContentCodesAnalyzer.java View source code |
/**
* @param args
* the command line arguments
*/
public static void main(String[] args) throws Exception {
if (args.length == 0) {
FileDialog dialog = new FileDialog(new Frame(), "Select file...", FileDialog.LOAD);
dialog.show();
String d = dialog.getDirectory();
String f = dialog.getFile();
if (d != null && f != null) {
args = new String[] { d + f };
} else {
System.out.println("No file selected... Bye!");
System.exit(0);
}
}
HashMap knownChnunks = getContentCodes();
HashMap newChunks = readNewChunks(new File(args[0]));
Iterator it = null;
/*
* System.out.println("\n+++ KNOWN CHUNKS +++\n");
*
* it = knownChnunks.keySet().iterator(); while(it.hasNext()) {
* System.out.println(knownChnunks.get(it.next())); }
*
* System.out.println("\n+++ NEW CHUNKS +++\n");
*
*
* it = newChunks.keySet().iterator(); while(it.hasNext()) {
* System.out.println(newChunks.get(it.next())); }
*/
List added = new ArrayList();
List removed = new ArrayList();
List changed = new ArrayList();
it = newChunks.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
Object obj = newChunks.get(key);
if (knownChnunks.containsKey(key) == false) {
added.add(obj);
} else {
Object obj2 = knownChnunks.get(key);
if (obj2.equals(obj) == false) {
changed.add(new Object[] { obj, obj2 });
}
}
}
it = knownChnunks.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
Object obj = knownChnunks.get(key);
if (newChunks.containsKey(key) == false) {
removed.add(obj);
}
}
System.out.println("\n+++ NEW CHUNKS +++\n");
it = added.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
System.out.println("\n+++ REMOVED CHUNKS +++\n");
it = removed.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
System.out.println("\n+++ CHANGED CHUNKS +++\n");
it = changed.iterator();
while (it.hasNext()) {
Object[] obj = (Object[]) it.next();
System.out.println("NEW: " + obj[0]);
System.out.println("OLD: " + obj[1]);
}
/*
* FileOutputStream os = new FileOutputStream(new File(
* "/Users/roger/foobar.txt")); byte[] dst = new byte[4];
* ByteUtil.toByteBE(SongCodecType.MPEG, dst, 0); os.write(dst, 0,
* dst.length);
*/
}Example 23
| Project: importlist-master File: MacOSDirectoryChooser.java View source code |
@Override
void chooseBaseDirectory() {
System.setProperty("apple.awt.fileDialogForDirectories", "true");
final FileDialog fileDialog = new FileDialog((Frame) null, this.getLocalizable().getDirectoryChooserTitle(), FileDialog.LOAD);
fileDialog.setModal(true);
fileDialog.setFilenameFilter(DirectoryValidator.INSTANCE);
try {
fileDialog.setDirectory(FileUtils.getUserDirectory().getAbsolutePath());
} catch (SecurityException e) {
LOG.log(Level.WARNING, e.getMessage(), e);
}
if (this.getBaseDirectory() != null) {
final File parentDirectory = this.getBaseDirectory().getParentFile();
if (parentDirectory != null) {
fileDialog.setDirectory(parentDirectory.getAbsolutePath());
}
}
fileDialog.setVisible(true);
System.setProperty("apple.awt.fileDialogForDirectories", "false");
if (fileDialog.getFile() == null) {
return;
}
this.getPrefs().setBaseDirectory(new File(fileDialog.getDirectory(), fileDialog.getFile()).getAbsolutePath());
LOG.info(String.format("Base directory is %s", this.getPrefs().getBaseDirectory()));
}Example 24
| Project: korsakow-editor-master File: OpenProjectFileAction.java View source code |
@Override
public void performAction() {
try {
if (!ExitAction.checkForChangesAndPrompt())
return;
} catch (MapperException e) {
Application.getInstance().showUnhandledErrorDialog(e);
return;
}
try {
FileDialog fileDialog = new FileDialog(Application.getInstance().getProjectExplorer());
fileDialog.setFilenameFilter(this);
if (Application.getInstance().getSaveFile() != null)
fileDialog.setDirectory(Application.getInstance().getSaveFile().getPath());
fileDialog.setMode(FileDialog.LOAD);
fileDialog.setFile(DataRegistry.getFile().getName());
fileDialog.setVisible(true);
if (fileDialog.getFile() == null)
return;
File file = new File(fileDialog.getDirectory(), fileDialog.getFile());
performAction(file);
} catch (Throwable e) {
Application.getInstance().showUnhandledErrorDialog(LanguageBundle.getString("general.errors.cantopen.title"), e);
ProjectLoader.newProject();
}
}Example 25
| Project: mssqldiff-master File: CsvCreateDialog.java View source code |
public void actionPerformed(java.awt.event.ActionEvent e) {
FileDialog fileDialog = new FileDialog(CsvCreateDialog.this, "Select CSV file", FileDialog.SAVE);
fileDialog.setFile(null);
fileDialog.setVisible(true);
filePathLabel.setText(fileDialog.getFile() == null ? null : fileDialog.getDirectory() + fileDialog.getFile());
fileDialog.dispose();
}Example 26
| Project: openmap-master File: LoadPropertiesMenuItem.java View source code |
public void actionPerformed(ActionEvent ae) {
//Collect properties
if (mapHandler == null) {
return;
}
PropertyHandler ph = null;
Iterator it = mapHandler.iterator();
while (it.hasNext()) {
Object someObj = it.next();
if (someObj instanceof PropertyHandler) {
ph = (PropertyHandler) someObj;
break;
}
}
if (ph == null) {
Debug.error("Couldn't find PropertyHandler");
return;
}
FileDialog fd = new FileDialog(new Frame(), "Loading the map from a Properties file...", FileDialog.LOAD);
fd.setVisible(true);
String fileName = fd.getFile();
String dirName = fd.getDirectory();
if (fileName == null) {
Debug.message("loadpropertiesmenuitem", "User did not select any file");
return;
}
Debug.message("loadpropertiesmenuitem", "User selected file " + dirName + File.separator + fileName);
File file = new File(new File(dirName), fileName);
try {
Properties newProps = new Properties();
FileInputStream fis = new FileInputStream(file);
newProps.load(fis);
String test = newProps.getProperty("openmap." + LayerHandler.layersProperty);
if (test == null) {
throw new IOException("Doesn't seem like a valid properties file");
}
// Just reset the projection and layers, not the
// components.
ph.loadProjectionAndLayers(mapHandler, newProps);
} catch (FileNotFoundException fnfe) {
Debug.error(fnfe.getMessage());
} catch (IOException ioe) {
InformationDelegator id = (InformationDelegator) mapHandler.get("com.bbn.openmap.InformationDelegator");
if (id != null) {
id.displayMessage("Error loading file...", "Error occurred loading " + file.getAbsolutePath() + "\n" + ioe.getMessage());
}
Debug.error("Error occurred loading " + file.getAbsolutePath());
}
}Example 27
| Project: vzome-desktop-master File: ZomicEditorPanel.java View source code |
private String readFromFile() {
// int returnVal = mFileChooser.showOpenDialog( ZomicEditorPanel.this );
// if (returnVal == JFileChooser.APPROVE_OPTION) {
// File file = mFileChooser.getSelectedFile();
//File file = mFileChooser.getSelectedFile();
mFileChooser.setTitle(OPEN);
mFileChooser.setMode(FileDialog.LOAD);
mFileChooser.setVisible(true);
String fileName = mFileChooser.getFile();
if (fileName != null) {
File file = new File(mFileChooser.getDirectory(), fileName);
String result = readTextFromFile(file);
if (result == null) {
JOptionPane.showMessageDialog(ZomicEditorPanel.this, "An exception prevented successful reading of the file.", "File read error", JOptionPane.ERROR_MESSAGE);
return null;
} else
return result;
}
return null;
}Example 28
| Project: xowa-master File: GfuiIoDialogUtl.java View source code |
public static Io_url SelectDir(Io_url startingDir) {
FileDialog openFileDialog = NewOpenFileDialog(startingDir);
// openFileDialog.FileName = @"press enter to select this folder";
openFileDialog.setVisible(true);
String selectedDir = openFileDialog.getDirectory();
// nothing selected
if (selectedDir == null)
return Io_url_.Empty;
Io_url selected = Io_url_.new_any_(selectedDir);
Io_url selectedFil = selected.GenSubFil(openFileDialog.getFile());
return selectedFil.OwnerDir();
}Example 29
| Project: AliView-master File: FileUtilities.java View source code |
public static File selectOpenFileViaChooser(File suggestedFile, Component parentComponent) {
File selectedFile = null;
// Only for some Windos VM is it used
if (OSNativeUtils.isRunningDefectJFilechooserJVM()) {
// get Frame
Component root = SwingUtilities.getRoot(parentComponent);
Frame parentFrame = null;
if (root instanceof Frame) {
parentFrame = (Frame) root;
}
// use the native file dialog
FileDialog dialog = new FileDialog(parentFrame, "Open", FileDialog.LOAD);
dialog.setDirectory(suggestedFile.getParent());
dialog.setVisible(true);
String fileDirectory = dialog.getDirectory();
String fileName = dialog.getFile();
if (fileName != null) {
selectedFile = new File(fileDirectory, fileName);
}
} else {
// Else JFileChooser
// Set readOnly to avoid rename of file by slow double click
Boolean old = UIManager.getBoolean("FileChooser.readOnly");
UIManager.put("FileChooser.readOnly", Boolean.TRUE);
JFileChooser fc = new JFileChooser(suggestedFile);
fc.setPreferredSize(new Dimension(preferedWidth, preferedHeight));
/*
AbstractButton button = SwingUtilities.getDescendantOfType(AbstractButton.class,
fc, "Icon", UIManager.getIcon("FileChooser.detailsViewIcon"));
button.doClick();
*/
int returnVal = fc.showOpenDialog(parentComponent);
UIManager.put("FileChooser.readOnly", old);
if (returnVal == JFileChooser.APPROVE_OPTION) {
selectedFile = fc.getSelectedFile();
} else {
selectedFile = null;
}
preferedWidth = fc.getSize().width;
preferedHeight = fc.getSize().height;
}
System.out.println("selectedfile" + selectedFile);
return selectedFile;
}Example 30
| Project: Atom2DEditor-master File: EffectPanel.java View source code |
void openEffect() {
FileDialog dialog = new FileDialog(editor, "Open Effect", FileDialog.LOAD);
if (lastDir != null) {
dialog.setDirectory(lastDir);
}
dialog.setVisible(true);
final String file = dialog.getFile();
final String dir = dialog.getDirectory();
if (dir == null || file == null || file.trim().length() == 0) {
return;
}
lastDir = dir;
ParticleEffect effect = new ParticleEffect();
try {
//FIXME: Use AssetManager instead.
//effect.loadEmitters(Gdx.files.absolute(new File(dir, file).getAbsolutePath()));
editor.effect = effect;
emitterTableModel.getDataVector().removeAllElements();
editor.particleData.clear();
} catch (Exception ex) {
System.out.println("Error loading effect: " + new File(dir, file).getAbsolutePath());
ex.printStackTrace();
JOptionPane.showMessageDialog(editor, "Error opening effect.");
return;
}
float viewportHeight = editor.worldCamera.getViewPortBottom() - editor.worldCamera.getViewPortTop();
float viewportWidth = editor.worldCamera.getFrustumRight() - editor.worldCamera.getFrustumLeft();
for (ParticleEmitter emitter : effect.getEmitters()) {
emitter.setPosition(viewportWidth / 2, viewportHeight / 2);
emitterTableModel.addRow(new Object[] { emitter.getName(), true });
}
editIndex = 0;
emitterTable.getSelectionModel().setSelectionInterval(editIndex, editIndex);
editor.reloadRows();
}Example 31
| Project: beast2-master File: Utils.java View source code |
public static File[] getFile(String message, boolean isLoadNotSave, File defaultFileOrDir, boolean allowMultipleSelection, String description, final String... extensions) {
if (isMac()) {
java.awt.Frame frame = new java.awt.Frame();
java.awt.FileDialog chooser = new java.awt.FileDialog(frame, message, (isLoadNotSave ? java.awt.FileDialog.LOAD : java.awt.FileDialog.SAVE));
if (defaultFileOrDir != null) {
if (defaultFileOrDir.isDirectory()) {
chooser.setDirectory(defaultFileOrDir.getAbsolutePath());
} else {
chooser.setDirectory(defaultFileOrDir.getParentFile().getAbsolutePath());
chooser.setFile(defaultFileOrDir.getName());
}
}
if (description != null) {
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
for (int i = 0; i < extensions.length; i++) {
if (name.toLowerCase().endsWith(extensions[i].toLowerCase())) {
return true;
}
}
return false;
}
};
chooser.setFilenameFilter(filter);
}
chooser.setMultipleMode(allowMultipleSelection);
chooser.setVisible(true);
if (chooser.getFile() == null)
return null;
if (allowMultipleSelection) {
return chooser.getFiles();
}
File file = new java.io.File(chooser.getDirectory(), chooser.getFile());
chooser.dispose();
frame.dispose();
return new File[] { file };
} else {
// No file name in the arguments so throw up a dialog box...
java.awt.Frame frame = new java.awt.Frame();
frame.setTitle(message);
final JFileChooser chooser = new JFileChooser(defaultFileOrDir);
chooser.setMultiSelectionEnabled(allowMultipleSelection);
if (description != null && extensions.length > 1 && extensions[0].length() > 0) {
FileNameExtensionFilter filter = new FileNameExtensionFilter(description, extensions);
chooser.setFileFilter(filter);
}
if (isLoadNotSave) {
if (chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
frame.dispose();
if (allowMultipleSelection) {
return chooser.getSelectedFiles();
} else {
if (chooser.getSelectedFile() == null) {
return null;
}
return new File[] { chooser.getSelectedFile() };
}
}
} else {
if (chooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
frame.dispose();
if (allowMultipleSelection) {
return chooser.getSelectedFiles();
} else {
if (chooser.getSelectedFile() == null) {
return null;
}
return new File[] { chooser.getSelectedFile() };
}
}
}
}
return null;
}Example 32
| Project: Folding-Map-master File: OpenMap.java View source code |
/**
* Opens up a File Dialog to prompt the user to select a map file to open.
*
* @param parentWindow
* @param userConfig User config option, can be null.
* @return A string with the path and file name to open.
*/
public static String promptUserForMapFile(JFrame parentWindow, UserConfig userConfig) {
FileExtensionFilter fileExtensionFilter;
FileDialog fileDialog;
String fileName;
fileName = null;
try {
fileDialog = new FileDialog(parentWindow);
fileExtensionFilter = new FileExtensionFilter();
if (userConfig != null)
fileDialog.setDirectory(userConfig.getWorkingDIR());
//Add acceptable file extentions
fileExtensionFilter.addExtension("fmxml");
fileExtensionFilter.addExtension("gpx");
fileExtensionFilter.addExtension("kml");
fileExtensionFilter.addExtension("kmz");
fileExtensionFilter.addExtension("mbtiles");
fileExtensionFilter.addExtension("osm");
fileExtensionFilter.addExtension("shp");
fileDialog.setFilenameFilter(fileExtensionFilter);
fileDialog.setVisible(true);
if (fileDialog.getFile() != null)
fileName = fileDialog.getDirectory() + fileDialog.getFile();
if (userConfig != null) {
userConfig.setWorkingDIR(fileDialog.getDirectory());
userConfig.addRecentFile(fileName);
}
} catch (Exception e) {
Logger.log(Logger.ERR, "Error in OpenMap.promptUserForMapFile()");
}
return fileName;
}Example 33
| Project: GdxStudio-master File: EffectPanel.java View source code |
void openEffect() {
FileDialog dialog = new FileDialog((Frame) null, "Open Effect", FileDialog.LOAD);
if (lastDir != null)
dialog.setDirectory(lastDir);
dialog.setVisible(true);
final String file = dialog.getFile();
final String dir = dialog.getDirectory();
if (dir == null || file == null || file.trim().length() == 0)
return;
lastDir = dir;
ParticleEffect effect = new ParticleEffect();
try {
effect.loadEmitters(Gdx.files.absolute(new File(dir, file).getAbsolutePath()));
editor.effect = effect;
emitterTableModel.getDataVector().removeAllElements();
editor.particleData.clear();
} catch (Exception ex) {
System.out.println("Error loading effect: " + new File(dir, file).getAbsolutePath());
ex.printStackTrace();
JOptionPane.showMessageDialog(editor, "Error opening effect.");
return;
}
for (ParticleEmitter emitter : effect.getEmitters()) {
emitter.setPosition(editor.worldCamera.viewportWidth / 2, editor.worldCamera.viewportHeight / 2);
emitterTableModel.addRow(new Object[] { emitter.getName(), true });
}
editIndex = 0;
emitterTable.getSelectionModel().setSelectionInterval(editIndex, editIndex);
editor.reloadRows();
}Example 34
| Project: gitools-master File: FileChooserUtils.java View source code |
private static FileChoose selectFileAWT(String title, String currentPath, String fileName, int mode) {
final FileDialog dialog = new java.awt.FileDialog(Application.get(), title, (mode == MODE_OPEN ? FileDialog.LOAD : FileDialog.SAVE));
dialog.setDirectory(currentPath);
dialog.setMultipleMode(false);
dialog.setAlwaysOnTop(true);
dialog.requestFocus();
dialog.toFront();
dialog.repaint();
dialog.setVisible(true);
if (fileName != null) {
dialog.setFile(fileName);
}
String file = dialog.getFile();
return (file == null ? null : new FileChoose(new File(dialog.getDirectory(), dialog.getFile()), null));
}Example 35
| Project: jolivia-master File: PacketAnalyzer.java View source code |
public static void main(String[] args) {
try {
File file;
if (args.length == 0) {
FileDialog dialog = new FileDialog(new Frame(), "Select file...", FileDialog.LOAD);
dialog.setVisible(true);
String d = dialog.getDirectory();
String f = dialog.getFile();
if (d != null && f != null) {
args = new String[] { d + f };
} else {
System.out.println("No file selected... Bye!");
System.exit(0);
}
}
file = new File(args[0]);
String result = process(file);
System.out.println(result);
} catch (Throwable t) {
t.printStackTrace();
} finally {
System.exit(0);
}
}Example 36
| Project: libgdx-master File: PreAlpha.java View source code |
protected void save() {
FileDialog dialog = new FileDialog(this, "Save Image", FileDialog.SAVE);
if (lastDir != null)
dialog.setDirectory(lastDir);
dialog.setVisible(true);
final String file = dialog.getFile();
final String dir = dialog.getDirectory();
if (dir == null || file == null || file.trim().length() == 0)
return;
lastDir = dir;
try {
generatePremultiplyAlpha(new File(dir, file));
JOptionPane.showMessageDialog(this, "Conversion complete!");
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error saving image.");
return;
}
}Example 37
| Project: misc_hookons_avec_javasnoop-master File: UIUtil.java View source code |
public static File getFileSelection(JFrame parent, boolean onlyDirectories, String startingDir) {
if (System.getProperty("os.name").toLowerCase().indexOf("mac") != -1) {
FileDialog fileDialog = new FileDialog(parent, "Select directory to dump source into", FileDialog.LOAD);
fileDialog.setDirectory(startingDir);
fileDialog.setVisible(true);
if (fileDialog.getFile() != null) {
return new File(fileDialog.getFile());
}
} else {
JFileChooser fc = new JFileChooser(new File(startingDir));
fc.setDialogTitle("Select directory to dump source into");
if (onlyDirectories)
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int rc = fc.showOpenDialog(parent);
if (rc == JFileChooser.APPROVE_OPTION) {
return fc.getSelectedFile();
}
}
return null;
}Example 38
| Project: myrobotlab-master File: FileUtil.java View source code |
public static String open(JFrame frame, String filter) {
FileDialog file = new FileDialog(frame, "Open File", FileDialog.LOAD);
// Set initial filename filter
file.setFile(filter);
// Blocks
file.setVisible(true);
String curFile;
if ((curFile = file.getFile()) != null) {
String newfilename = file.getDirectory() + curFile;
char[] data;
// setCursor (Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
File f = new File(newfilename);
try {
FileReader fin = new FileReader(f);
int filesize = (int) f.length();
data = new char[filesize];
fin.read(data, 0, filesize);
log.info("Loaded: " + newfilename);
setLastFileOpened(newfilename);
// avoid leaky file handles.
fin.close();
return new String(data);
} catch (FileNotFoundException exc) {
lastStatus = "File Not Found: " + newfilename;
log.error(lastStatus);
} catch (IOException exc) {
lastStatus = "IOException: " + newfilename;
log.error(lastStatus);
}
// setCursor (Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
return null;
}Example 39
| Project: openjdk-master File: DimensionEncapsulation.java View source code |
@Override
public void run() {
runTest(new Panel());
runTest(new Button());
runTest(new Checkbox());
runTest(new Canvas());
runTest(new Choice());
runTest(new Label());
runTest(new Scrollbar());
runTest(new TextArea());
runTest(new TextField());
runTest(new Dialog(new JFrame()));
runTest(new Frame());
runTest(new Window(new JFrame()));
runTest(new FileDialog(new JFrame()));
runTest(new List());
runTest(new ScrollPane());
runTest(new JFrame());
runTest(new JDialog(new JFrame()));
runTest(new JWindow(new JFrame()));
runTest(new JLabel("hi"));
runTest(new JMenu());
runTest(new JTree());
runTest(new JTable());
runTest(new JMenuItem());
runTest(new JCheckBoxMenuItem());
runTest(new JToggleButton());
runTest(new JSpinner());
runTest(new JSlider());
runTest(Box.createVerticalBox());
runTest(Box.createHorizontalBox());
runTest(new JTextField());
runTest(new JTextArea());
runTest(new JTextPane());
runTest(new JPasswordField());
runTest(new JFormattedTextField());
runTest(new JEditorPane());
runTest(new JButton());
runTest(new JColorChooser());
runTest(new JFileChooser());
runTest(new JCheckBox());
runTest(new JInternalFrame());
runTest(new JDesktopPane());
runTest(new JTableHeader());
runTest(new JLayeredPane());
runTest(new JRootPane());
runTest(new JMenuBar());
runTest(new JOptionPane());
runTest(new JRadioButton());
runTest(new JRadioButtonMenuItem());
runTest(new JPopupMenu());
//runTest(new JScrollBar()); --> don't test defines max and min in
// terms of preferred
runTest(new JScrollPane());
runTest(new JViewport());
runTest(new JSplitPane());
runTest(new JTabbedPane());
runTest(new JToolBar());
runTest(new JSeparator());
runTest(new JProgressBar());
if (!failures.isEmpty()) {
System.out.println("These classes failed");
for (final Component failure : failures) {
System.out.println(failure.getClass());
}
throw new RuntimeException("Test failed");
}
}Example 40
| Project: openpnp-master File: GcodeDriverConfigurationWizard.java View source code |
@Override
public void actionPerformed(ActionEvent arg0) {
try {
FileDialog fileDialog = new FileDialog(MainFrame.get(), "Save Gcode Profile As...", FileDialog.SAVE);
fileDialog.setFilenameFilter(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".xml");
}
});
fileDialog.setVisible(true);
String filename = fileDialog.getFile();
if (filename == null) {
return;
}
if (!filename.toLowerCase().endsWith(".xml")) {
filename = filename + ".xml";
}
File file = new File(new File(fileDialog.getDirectory()), filename);
if (file.exists()) {
int ret = JOptionPane.showConfirmDialog(getTopLevelAncestor(), file.getName() + " already exists. Do you want to replace it?", "Replace file?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (ret != JOptionPane.YES_OPTION) {
return;
}
}
Serializer s = Configuration.createSerializer();
FileWriter w = new FileWriter(file);
s.write(driver, w);
w.close();
} catch (Exception e) {
MessageBoxes.errorBox(MainFrame.get(), "Export Failed", e);
}
}Example 41
| Project: pelican-master File: FileChooserToolBox.java View source code |
public static File openSaveFileChooser(JFrame parent) {
File f = null;
if (fileChooser == null)
prepareChooser(parent);
fileChooser.setMode(FileDialog.SAVE);
fileChooser.setTitle("Save file here...");
//fileChooser.showSaveDialog(parent);
fileChooser.setVisible(true);
//if(returnVal == JFileChooser.APPROVE_OPTION)
// f=fileChooser.getSelectedFile();
String fname = fileChooser.getFile();
if (fname != null)
f = new File(fileChooser.getDirectory() + File.separatorChar + fname);
/*if (f!=null && f.exists())
{
int n = JOptionPane.showConfirmDialog(
null,
"Warning file: " + f.getName() + " already exists. Do you want to overwrite it?",
"Saving or not saving",
JOptionPane.YES_NO_OPTION);
if (n!=0)
f=null;
}*/
return f;
}Example 42
| Project: Penn-TotalRecall-master File: OpenAudioLocationAction.java View source code |
/**
* Performs <code>Action</code> by attempting to open the file chooser on the directory the last audio location selection was made in.
* Failing that, uses current directory.
* Afterwards adds the selected files and requests the list be sorted.
*/
@Override
public void actionPerformed(ActionEvent e) {
super.actionPerformed(e);
String maybeLastPath = UserPrefs.prefs.get(UserPrefs.openLocationPath, SysInfo.sys.userHomeDir);
if (new File(maybeLastPath).exists() == false) {
maybeLastPath = SysInfo.sys.userHomeDir;
}
String path = null;
if (mode != SelectionMode.FILES_AND_DIRECTORIES) {
String title;
if (mode == SelectionMode.DIRECTORIES_ONLY) {
//exclusively directories then!
System.setProperty("apple.awt.fileDialogForDirectories", "true");
title = "Open Audio Folder";
} else {
title = "Open Audio File";
}
FileDialog fd = new FileDialog(MyFrame.getInstance(), title, FileDialog.LOAD);
fd.setFilenameFilter(new FilenameFilter() {
public boolean accept(File dir, String name) {
if (mode == SelectionMode.DIRECTORIES_ONLY) {
return name == null;
} else {
for (String ext : Constants.audioFormatsLowerCase) {
if (name.toLowerCase().endsWith(ext)) {
return true;
}
}
return false;
}
}
});
fd.setDirectory(maybeLastPath);
fd.setMode(FileDialog.LOAD);
fd.setVisible(true);
String dir = fd.getDirectory();
String file = fd.getFile();
if (dir != null && file != null) {
path = fd.getDirectory() + fd.getFile();
}
System.setProperty("apple.awt.fileDialogForDirectories", "false");
} else {
JFileChooser jfc = new JFileChooser(maybeLastPath);
jfc.setDialogTitle("Open Audio File or Folder");
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
jfc.setFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
} else {
for (String ext : Constants.audioFormatsLowerCase) {
if (f.getName().toLowerCase().endsWith(ext)) {
return true;
}
}
return false;
}
}
@Override
public String getDescription() {
return "Supported Audio Formats";
}
});
int result = jfc.showOpenDialog(MyFrame.getInstance());
if (result == JFileChooser.APPROVE_OPTION) {
path = jfc.getSelectedFile().getPath();
}
}
if (path != null) {
UserPrefs.prefs.put(UserPrefs.openLocationPath, new File(path).getParentFile().getPath());
File chosenFile = new File(path);
if (chosenFile.isFile()) {
AudioFileDisplay.addFilesIfSupported(new File[] { chosenFile });
} else if (chosenFile.isDirectory()) {
AudioFileDisplay.addFilesIfSupported(chosenFile.listFiles());
}
}
}Example 43
| Project: relax-decode-master File: GridViewer.java View source code |
public void actionPerformed(ActionEvent e) {
if (logger.isLoggable(Level.FINER))
logger.finer("Action: " + e.toString());
String actionCommand = e.getActionCommand();
if (actionCommand.equalsIgnoreCase(GridViewerMenu.openMenuItemName)) {
FileDialog dialog = new FileDialog(this, "Open", FileDialog.LOAD);
dialog.setFilenameFilter(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith("josh");
}
});
dialog.setVisible(true);
} else if (actionCommand.equalsIgnoreCase(GridViewerMenu.printMenuItemName)) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(gridScrollPanel);
boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException ex) {
logger.warning("Print job was unsuccessful: " + ex.getLocalizedMessage());
}
}
} else if (actionCommand.equalsIgnoreCase(GridViewerMenu.exitMenuItemName)) {
this.setVisible(false);
System.exit(0);
}
}Example 44
| Project: rj-core-master File: rtest.java View source code |
public String rChooseFile(Rengine re, int newFile) {
FileDialog fd = new FileDialog(new Frame(), (newFile == 0) ? "Select a file" : "Select a new file", (newFile == 0) ? FileDialog.LOAD : FileDialog.SAVE);
fd.setVisible(true);
String res = null;
if (fd.getDirectory() != null)
res = fd.getDirectory();
if (fd.getFile() != null)
res = (res == null) ? fd.getFile() : (res + fd.getFile());
return res;
}Example 45
| Project: SketchChair-master File: Environments.java View source code |
public void openEnvironmentFromFile(GUIEvent e) {
LOGGER.info("Preparing to open SketchChair file.");
FileDialog fd = new FileDialog(GLOBAL.applet.frame, "open", FileDialog.LOAD);
fd.setFile("chair" + SETTINGS.chairSaveNum + ".png");
String currentDir = new File(".").getAbsolutePath();
fd.setDirectory(currentDir + "\\savedChairs\\");
/*
fd.setFilenameFilter(new FilenameFilter(){
public boolean accept(File directory, String filename)
{
return (filename.endsWith("*.cha"));
}
});
*/
fd.setLocation(50, 50);
fd.pack();
fd.show();
//System.out.println(fd.getDirectory() +fd.getFile());
if (fd.getName() != null) {
String filename = fd.getFile();
LOGGER.info("Loading: " + fd.getDirectory() + filename);
Environment environment = new Environment(fd.getDirectory() + filename, GLOBAL.applet);
this.l.add(environment);
} else {
// println("not an stl file");
}
}Example 46
| Project: Soen6471Frinika-master File: AudioPlayBackExampleDA.java View source code |
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// Create the audio context
final VoiceServer voiceServer = new AudioContext().getVoiceServer();
// Create the project container
final ProjectContainer proj = new ProjectContainer();
String nl = System.getProperty("line.separator");
String fileSeparator = System.getProperty("file.separator");
String selectFileDir;
String selectFile;
RandomAccessFile fis = null;
Frame myFrame = new Frame("Parent Frame");
FileDialog myFD;
myFrame.setSize(200, 200);
// myFrame.show() ;
myFrame.setVisible(false);
myFD = new FileDialog(myFrame, "Open a Wav");
// this blocks main program thread until select.
myFD.setVisible(true);
// determine is file directory
selectFileDir = myFD.getDirectory();
if (selectFileDir.charAt(selectFileDir.length() - 1) != fileSeparator.charAt(0))
selectFileDir += fileSeparator;
selectFile = selectFileDir + myFD.getFile();
try {
fis = new RandomAccessFile(selectFile, "r");
DAudioReader dar = new DAudioReader(fis);
// PJS: This is broken since this is now using Toot
/* final DAAudioStreamVoice voice = new DAAudioStreamVoice(
voiceServer, (FrinikaSequencer) (proj.getSequencer()),
*/
new ProjectFrame(proj);
} catch (IOException ie) {
} finally {
myFrame.dispose();
// fis.close();
}
}Example 47
| Project: touhou-java-master File: EffectPanel.java View source code |
void openEffect() {
FileDialog dialog = new FileDialog(editor, "Open Effect", FileDialog.LOAD);
if (lastDir != null)
dialog.setDirectory(lastDir);
dialog.setVisible(true);
final String file = dialog.getFile();
final String dir = dialog.getDirectory();
if (dir == null || file == null || file.trim().length() == 0)
return;
lastDir = dir;
ParticleEffect effect = new ParticleEffect();
try {
effect.loadEmitters(Gdx.files.absolute(new File(dir, file).getAbsolutePath()));
editor.effect = effect;
emitterTableModel.getDataVector().removeAllElements();
editor.particleData.clear();
} catch (Exception ex) {
System.out.println("Error loading effect: " + new File(dir, file).getAbsolutePath());
ex.printStackTrace();
JOptionPane.showMessageDialog(editor, "Error opening effect.");
return;
}
for (ParticleEmitter emitter : effect.getEmitters()) {
emitter.setPosition(editor.worldCamera.viewportWidth / 2, editor.worldCamera.viewportHeight / 2);
emitterTableModel.addRow(new Object[] { emitter.getName(), true });
}
editIndex = 0;
emitterTable.getSelectionModel().setSelectionInterval(editIndex, editIndex);
editor.reloadRows();
}Example 48
| Project: archiv-editor-master File: BaseXFileChooser.java View source code |
/**
* Selects a file or directory.
* @param mode type defined by {@link Mode}
* @return resulting input reference
*/
public IOFile select(final Mode mode) {
IOFile io;
if (fd != null) {
if (mode == Mode.FDOPEN)
fd.setFile(" ");
fd.setMode(mode == Mode.FSAVE || mode == Mode.DSAVE ? FileDialog.SAVE : FileDialog.LOAD);
fd.setVisible(true);
final String f = fd.getFile();
if (f == null)
return null;
final String dir = fd.getDirectory();
return new IOFile(mode == Mode.DOPEN || mode == Mode.DSAVE ? dir : dir + '/' + fd.getFile());
}
int state = 0;
switch(mode) {
case FOPEN:
state = fc.showOpenDialog(gui);
break;
case FDOPEN:
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
state = fc.showOpenDialog(gui);
break;
case FSAVE:
state = fc.showSaveDialog(gui);
break;
case DOPEN:
case DSAVE:
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
state = fc.showDialog(gui, null);
break;
}
if (state != JFileChooser.APPROVE_OPTION)
return null;
io = new IOFile(fc.getSelectedFile().getPath());
if (mode != Mode.FSAVE)
return io;
// add file suffix to file to be saved
if (suffix != null && !io.path().contains("."))
io = new IOFile(io.path() + suffix);
// show replace dialog
return !io.exists() || Dialog.confirm(gui, Util.info(FILE_EXISTS_X, io)) ? io : null;
}Example 49
| Project: assertj-swing-master File: ContextMonitor_eventDispatched_Test.java View source code |
@Test
public void shouldProcessEventWithIdEqualToWindowOpenedAndMarkWindowAsReadyIfWindowIsFileDialog() {
Window w = new FileDialog(window);
when(context.storedQueueFor(w)).thenReturn(w.getToolkit().getSystemEventQueue());
monitor.eventDispatched(new ComponentEvent(w, WINDOW_OPENED));
verify(context).addContextFor(w);
verify(windows).attachNewWindowVisibilityMonitor(w);
verify(windows).markAsShowing(w);
verify(windows).markAsReady(w);
}Example 50
| Project: chipKIT32-MAX-master File: Archiver.java View source code |
public void run() {
Sketch sketch = editor.getSketch();
// first save the sketch so that things don't archive strangely
boolean success = false;
try {
success = sketch.save();
} catch (Exception e) {
e.printStackTrace();
}
if (!success) {
Base.showWarning("Couldn't archive sketch", "Archiving the sketch has been canceled because\n" + "the sketch couldn't save properly.", null);
return;
}
File location = sketch.getFolder();
String name = location.getName();
File parent = new File(location.getParent());
//System.out.println("loc " + location);
//System.out.println("par " + parent);
File newbie = null;
String namely = null;
int index = 0;
do {
// only use the date if the sketch name isn't the default name
useDate = !name.startsWith("sketch_");
if (useDate) {
String purty = dateFormat.format(new Date());
String stamp = purty + ((char) ('a' + index));
namely = name + "-" + stamp;
newbie = new File(parent, namely + ".zip");
} else {
String diggie = numberFormat.format(index + 1);
namely = name + "-" + diggie;
newbie = new File(parent, namely + ".zip");
}
index++;
} while (newbie.exists());
// open up a prompt for where to save this fella
FileDialog fd = new FileDialog(editor, "Archive sketch as:", FileDialog.SAVE);
fd.setDirectory(parent.getAbsolutePath());
fd.setFile(newbie.getName());
fd.setVisible(true);
String directory = fd.getDirectory();
String filename = fd.getFile();
// only write the file if not canceled
if (filename != null) {
newbie = new File(directory, filename);
try {
//System.out.println(newbie);
FileOutputStream zipOutputFile = new FileOutputStream(newbie);
ZipOutputStream zos = new ZipOutputStream(zipOutputFile);
// recursively fill the zip file
buildZip(location, name, zos);
// close up the jar file
zos.flush();
zos.close();
editor.statusNotice("Created archive " + newbie.getName() + ".");
} catch (IOException e) {
e.printStackTrace();
}
} else {
editor.statusNotice("Archive sketch canceled.");
}
}Example 51
| Project: EnrichmentMapApp-master File: FileBrowser.java View source code |
private Optional<File> browseForRootFolderMac(Component parent) {
final String property = System.getProperty("apple.awt.fileDialogForDirectories");
System.setProperty("apple.awt.fileDialogForDirectories", "true");
try {
FileDialog chooser;
if (parent instanceof Dialog)
chooser = new FileDialog((Dialog) parent, "Choose Root Folder", FileDialog.LOAD);
else if (parent instanceof Frame)
chooser = new FileDialog((Frame) parent, "Choose Root Folder", FileDialog.LOAD);
else
throw new IllegalArgumentException("parent must be Dialog or Frame");
chooser.setDirectory(getCurrentDirectory().getAbsolutePath());
chooser.setModal(true);
chooser.setLocationRelativeTo(parent);
chooser.setVisible(true);
String file = chooser.getFile();
String dir = chooser.getDirectory();
if (file == null || dir == null) {
return Optional.empty();
}
setCurrentDirectory(new File(dir));
return Optional.of(new File(dir + File.separator + file));
} finally {
if (property != null) {
System.setProperty("apple.awt.fileDialogForDirectories", property);
}
}
}Example 52
| Project: fcrepo-before33-master File: BatchBuildIngestGUI.java View source code |
protected void pidsAction() {
try {
FileDialog dlg = new FileDialog(Administrator.INSTANCE, "PIDs Output File", FileDialog.SAVE);
if (Administrator.batchtoolLastDir != null) {
dlg.setDirectory(Administrator.batchtoolLastDir.getPath());
}
dlg.setVisible(true);
String temp = dlg.getFile();
if (temp != null) {
File dir = new File(dlg.getDirectory());
m_pidsField.setText(new File(dir, temp).getPath());
Administrator.batchtoolLastDir = dir;
}
} catch (Exception e) {
m_pidsField.setText("");
}
}Example 53
| Project: fcrepo-master File: BatchBuildIngestGUI.java View source code |
protected void pidsAction() {
try {
FileDialog dlg = new FileDialog(Administrator.INSTANCE, "PIDs Output File", FileDialog.SAVE);
if (Administrator.batchtoolLastDir != null) {
dlg.setDirectory(Administrator.batchtoolLastDir.getPath());
}
dlg.setVisible(true);
String temp = dlg.getFile();
if (temp != null) {
File dir = new File(dlg.getDirectory());
m_pidsField.setText(new File(dir, temp).getPath());
Administrator.batchtoolLastDir = dir;
}
} catch (Exception e) {
m_pidsField.setText("");
}
}Example 54
| Project: fest-swing-1.x-master File: ContextMonitor_eventDispatched_Test.java View source code |
@Test
public void shouldProcessEventWithIdEqualToWindowOpenedAndMarkWindowAsReadyIfWindowIsFileDialog() {
Window w = new FileDialog(window);
when(context.storedQueueFor(w)).thenReturn(w.getToolkit().getSystemEventQueue());
monitor.eventDispatched(new ComponentEvent(w, WINDOW_OPENED));
verify(context).addContextFor(w);
verify(windows).attachNewWindowVisibilityMonitor(w);
verify(windows).markAsShowing(w);
verify(windows).markAsReady(w);
}Example 55
| Project: gsn-master File: REngineManager.java View source code |
public String rChooseFile(Rengine re, int newFile) {
FileDialog fd = new FileDialog(new Frame(), (newFile == 0) ? "Select a file" : "Select a new file", (newFile == 0) ? FileDialog.LOAD : FileDialog.SAVE);
fd.setVisible(true);
String res = null;
if (fd.getDirectory() != null)
res = fd.getDirectory();
if (fd.getFile() != null)
res = (res == null) ? fd.getFile() : (res + fd.getFile());
return res;
}Example 56
| Project: iambookmaster-master File: FileExchange.java View source code |
public Object run() {
try {
buffer = null;
Frame parent = new Frame();
FileDialog fd = new FileDialog(parent, title, save ? FileDialog.SAVE : FileDialog.LOAD);
fd.setVisible(true);
String selectedItem = fd.getFile();
if (selectedItem == null) {
return null;
} else {
buffer = fd.getDirectory() + selectedItem;
return RESULT_OK;
}
} catch (Exception e) {
return e.getMessage();
}
}Example 57
| Project: igv-master File: PaletteToolFrame.java View source code |
private void saveItemActionPerformed(ActionEvent e) {
java.util.List<ColorPanel.Palette> paletteList = colorPanel.paletteList;
if (paletteList != null) {
java.awt.FileDialog fd = new FileDialog(this);
fd.setMode(FileDialog.SAVE);
fd.setVisible(true);
String f = fd.getFile();
if (f != null) {
try {
File file = new File(fd.getDirectory(), f);
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
for (ColorPanel.Palette p : paletteList) {
pw.println(p.label);
for (ColorPanel.Swatch s : p.swatches) {
pw.println(ColorUtilities.colorToString(s.color));
}
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}Example 58
| Project: java-uniuploader-master File: pnlWoWDirectories.java View source code |
private void btnAddDirectoryActionPerformed(ActionEvent evt) {
if (evt.getSource() == this.btnAddDirectory) {
boolean failed = false;
boolean mac = Util.isMac();
if (mac) {
java.awt.Frame f = jUniUploader.inst;
FileDialog fd = new FileDialog(f, "Select a World of Warcraft Directory", FileDialog.LOAD);
try {
fd.show();
String fileName = fd.getFile();
String rootDir = fd.getDirectory();
String completePath = (rootDir == null ? "" : rootDir) + (fileName == null ? "" : fileName);
log.debug("Adding OS X style " + completePath);
if (completePath != null) {
File file = new File(completePath);
if (file != null && file.exists() && file.isDirectory()) {
WDirectory wd = new WDirectory(file);
frmMain.wowDirectories.addElement(wd);
}
}
} catch (Exception ex) {
failed = true;
log.warn("Failed trying to display a FileDialog, falling back to JFileChooser", ex);
}
}
if (!mac || failed) {
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (file != null && file.exists() && file.isDirectory()) {
WDirectory wd = new WDirectory(file);
frmMain.wowDirectories.addElement(wd);
}
} else {
log.trace("Open command cancelled by user.");
}
}
}
}Example 59
| Project: JavaCL-master File: SobelFilterDemo.java View source code |
static File chooseFile() {
if (Platform.isMacOSX()) {
FileDialog d = new FileDialog((java.awt.Frame) null);
d.setMode(FileDialog.LOAD);
d.show();
String f = d.getFile();
if (f != null)
return new File(new File(d.getDirectory()), d.getFile());
} else {
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
return chooser.getSelectedFile();
}
return null;
}Example 60
| Project: jdk7u-jdk-master File: GtkFileDialogPeer.java View source code |
private void showNativeDialog() {
String dirname = fd.getDirectory();
// File path has a priority against directory path.
String filename = fd.getFile();
if (filename != null) {
final File file = new File(filename);
if (fd.getMode() == FileDialog.LOAD && dirname != null && file.getParent() == null) {
// File path for gtk_file_chooser_set_filename.
filename = dirname + (dirname.endsWith(File.separator) ? "" : File.separator) + filename;
}
if (fd.getMode() == FileDialog.SAVE && file.getParent() != null) {
// Filename for gtk_file_chooser_set_current_name.
filename = file.getName();
// Directory path for gtk_file_chooser_set_current_folder.
dirname = file.getParent();
}
}
GtkFileDialogPeer.this.run(fd.getTitle(), fd.getMode(), dirname, filename, fd.getFilenameFilter(), fd.isMultipleMode(), fd.getX(), fd.getY());
}Example 61
| Project: Kaleido-master File: Archiver.java View source code |
public void run() {
Sketch sketch = editor.getSketch();
// first save the sketch so that things don't archive strangely
boolean success = false;
try {
success = sketch.save();
} catch (Exception e) {
e.printStackTrace();
}
if (!success) {
Base.showWarning("Couldn't archive sketch", "Archiving the sketch has been canceled because\n" + "the sketch couldn't save properly.", null);
return;
}
File location = sketch.getFolder();
String name = location.getName();
File parent = new File(location.getParent());
//System.out.println("loc " + location);
//System.out.println("par " + parent);
File newbie = null;
String namely = null;
int index = 0;
do {
// only use the date if the sketch name isn't the default name
useDate = !name.startsWith("sketch_");
if (useDate) {
String purty = dateFormat.format(new Date());
String stamp = purty + ((char) ('a' + index));
namely = name + "-" + stamp;
newbie = new File(parent, namely + ".zip");
} else {
String diggie = numberFormat.format(index + 1);
namely = name + "-" + diggie;
newbie = new File(parent, namely + ".zip");
}
index++;
} while (newbie.exists());
// open up a prompt for where to save this fella
FileDialog fd = new FileDialog(editor, "Archive sketch as:", FileDialog.SAVE);
fd.setDirectory(parent.getAbsolutePath());
fd.setFile(newbie.getName());
fd.setVisible(true);
String directory = fd.getDirectory();
String filename = fd.getFile();
// only write the file if not canceled
if (filename != null) {
newbie = new File(directory, filename);
try {
//System.out.println(newbie);
FileOutputStream zipOutputFile = new FileOutputStream(newbie);
ZipOutputStream zos = new ZipOutputStream(zipOutputFile);
// recursively fill the zip file
buildZip(location, name, zos);
// close up the jar file
zos.flush();
zos.close();
editor.statusNotice("Created archive " + newbie.getName() + ".");
} catch (IOException e) {
e.printStackTrace();
}
} else {
editor.statusNotice("Archive sketch canceled.");
}
}Example 62
| Project: maple-ide-master File: Archiver.java View source code |
public void run() {
Sketch sketch = editor.getSketch();
// first save the sketch so that things don't archive strangely
boolean success = false;
try {
success = sketch.save();
} catch (Exception e) {
e.printStackTrace();
}
if (!success) {
Base.showWarning("Couldn't archive sketch", "Archiving the sketch has been canceled because\n" + "the sketch couldn't save properly.", null);
return;
}
File location = sketch.getFolder();
String name = location.getName();
File parent = new File(location.getParent());
//System.out.println("loc " + location);
//System.out.println("par " + parent);
File newbie = null;
String namely = null;
int index = 0;
do {
// only use the date if the sketch name isn't the default name
useDate = !name.startsWith("sketch_");
if (useDate) {
String purty = dateFormat.format(new Date());
String stamp = purty + ((char) ('a' + index));
namely = name + "-" + stamp;
newbie = new File(parent, namely + ".zip");
} else {
String diggie = numberFormat.format(index + 1);
namely = name + "-" + diggie;
newbie = new File(parent, namely + ".zip");
}
index++;
} while (newbie.exists());
// open up a prompt for where to save this fella
FileDialog fd = new FileDialog(editor, "Archive sketch as:", FileDialog.SAVE);
fd.setDirectory(parent.getAbsolutePath());
fd.setFile(newbie.getName());
fd.setVisible(true);
String directory = fd.getDirectory();
String filename = fd.getFile();
// only write the file if not canceled
if (filename != null) {
newbie = new File(directory, filename);
try {
//System.out.println(newbie);
FileOutputStream zipOutputFile = new FileOutputStream(newbie);
ZipOutputStream zos = new ZipOutputStream(zipOutputFile);
// recursively fill the zip file
buildZip(location, name, zos);
// close up the jar file
zos.flush();
zos.close();
editor.statusNotice("Created archive " + newbie.getName() + ".");
} catch (IOException e) {
e.printStackTrace();
}
} else {
editor.statusNotice("Archive sketch canceled.");
}
}Example 63
| Project: megameklab-master File: StatusBar.java View source code |
private void getFluffImage() {
//copied from structureTab
FileDialog fDialog = new FileDialog(getParentFrame(), "Image Path", FileDialog.LOAD);
fDialog.setDirectory(new File(ImageHelper.fluffPath).getAbsolutePath() + File.separatorChar + ImageHelper.imageMech + File.separatorChar);
/*
//This does not seem to be working
if (getMech().getFluff().getMMLImagePath().trim().length() > 0) {
String fullPath = new File(getMech().getFluff().getMMLImagePath()).getAbsolutePath();
String imageName = fullPath.substring(fullPath.lastIndexOf(File.separatorChar) + 1);
fullPath = fullPath.substring(0, fullPath.lastIndexOf(File.separatorChar) + 1);
fDialog.setDirectory(fullPath);
fDialog.setFile(imageName);
} else {
fDialog.setDirectory(new File(ImageHelper.fluffPath).getAbsolutePath() + File.separatorChar + ImageHelper.imageMech + File.separatorChar);
fDialog.setFile(getMech().getChassis() + " " + getMech().getModel() + ".png");
}
*/
fDialog.setLocationRelativeTo(this);
fDialog.setVisible(true);
if (fDialog.getFile() != null) {
String relativeFilePath = new File(fDialog.getDirectory() + fDialog.getFile()).getAbsolutePath();
relativeFilePath = "." + File.separatorChar + relativeFilePath.substring(new File(System.getProperty("user.dir").toString()).getAbsolutePath().length() + 1);
getMech().getFluff().setMMLImagePath(relativeFilePath);
}
refresh.refreshPreview();
return;
}Example 64
| Project: openflexo-master File: FlexoFileChooser.java View source code |
public void setDialogType(int type) {
if (getImplementationType() == ImplementationType.JFileChooserImplementation) {
_fileChooser.setDialogType(type);
} else if (getImplementationType() == ImplementationType.FileDialogImplementation) {
if (type == JFileChooser.SAVE_DIALOG) {
_fileDialog.setMode(FileDialog.SAVE);
}
if (type == JFileChooser.OPEN_DIALOG) {
_fileDialog.setMode(FileDialog.LOAD);
}
}
}Example 65
| Project: openjdk8-jdk-master File: GtkFileDialogPeer.java View source code |
private void showNativeDialog() {
String dirname = fd.getDirectory();
// File path has a priority against directory path.
String filename = fd.getFile();
if (filename != null) {
final File file = new File(filename);
if (fd.getMode() == FileDialog.LOAD && dirname != null && file.getParent() == null) {
// File path for gtk_file_chooser_set_filename.
filename = dirname + (dirname.endsWith(File.separator) ? "" : File.separator) + filename;
}
if (fd.getMode() == FileDialog.SAVE && file.getParent() != null) {
// Filename for gtk_file_chooser_set_current_name.
filename = file.getName();
// Directory path for gtk_file_chooser_set_current_folder.
dirname = file.getParent();
}
}
GtkFileDialogPeer.this.run(fd.getTitle(), fd.getMode(), dirname, filename, fd.getFilenameFilter(), fd.isMultipleMode(), fd.getX(), fd.getY());
}Example 66
| Project: SikuliX-2014-master File: SikulixFileChooser.java View source code |
private File showFileChooser(String title, int mode, int selectionMode, Object... filters) {
String last_dir = PreferencesUser.getInstance().get("LAST_OPEN_DIR", "");
Debug.log(3, "showFileChooser: %s at %s", title.split(" ")[0], last_dir);
JFileChooser fchooser = null;
File fileChoosen = null;
while (true) {
fchooser = new JFileChooser();
if (!last_dir.isEmpty()) {
fchooser.setCurrentDirectory(new File(last_dir));
}
fchooser.setSelectedFile(null);
fchooser.setDialogTitle(title);
boolean shouldTraverse = false;
String btnApprove = "Select";
if (isGeneric()) {
fchooser.setFileSelectionMode(DIRSANDFILES);
fchooser.setAcceptAllFileFilterUsed(true);
shouldTraverse = true;
} else {
if (Settings.isMac() && Settings.isJava7() && selectionMode == DIRS) {
selectionMode = DIRSANDFILES;
}
fchooser.setFileSelectionMode(selectionMode);
if (mode == FileDialog.SAVE) {
fchooser.setDialogType(JFileChooser.SAVE_DIALOG);
btnApprove = "Save";
}
if (filters.length == 0) {
fchooser.setAcceptAllFileFilterUsed(true);
shouldTraverse = true;
} else {
fchooser.setAcceptAllFileFilterUsed(false);
for (Object filter : filters) {
if (filter instanceof SikulixFileFilter) {
fchooser.addChoosableFileFilter((SikulixFileFilter) filter);
} else {
fchooser.setFileFilter((FileNameExtensionFilter) filter);
shouldTraverse = true;
}
}
}
}
if (shouldTraverse && Settings.isMac()) {
fchooser.putClientProperty("JFileChooser.packageIsTraversable", "always");
}
if (fchooser.showDialog(_parent, btnApprove) != JFileChooser.APPROVE_OPTION) {
return null;
}
fileChoosen = fchooser.getSelectedFile();
// folders must contain a valid scriptfile
if (!isGeneric() && mode == FileDialog.LOAD && !isValidScript(fileChoosen)) {
Sikulix.popError("Folder not a valid SikuliX script\nTry again.");
last_dir = fileChoosen.getParentFile().getAbsolutePath();
continue;
}
break;
}
String lastDir = fileChoosen.getParent();
if (null == lastDir) {
lastDir = fileChoosen.getAbsolutePath();
}
PreferencesUser.getInstance().put("LAST_OPEN_DIR", lastDir);
return fileChoosen;
}Example 67
| Project: spark-svn-mirror-master File: ChatRoomTransferDecorator.java View source code |
public void finished() {
FileDialog fileChooser = SparkManager.getTransferManager().getFileChooser(SparkManager.getChatManager().getChatContainer().getChatFrame(), Res.getString("title.select.file.to.send"));
fileChooser.setVisible(true);
if (fileChooser.getDirectory() == null || fileChooser.getFile() == null) {
return;
}
File file = new File(fileChooser.getDirectory(), fileChooser.getFile());
if (file.exists()) {
SparkManager.getTransferManager().setDefaultDirectory(file.getParentFile());
SparkManager.getTransferManager().sendFile(file, ((ChatRoomImpl) chatRoom).getParticipantJID());
}
}Example 68
| Project: triple-master File: TripleAMenuBar.java View source code |
public static File getSaveGameLocationDialog(final Frame frame) {
// is to use an AWT FileDialog instead of a Swing JDialog
if (SystemProperties.isMac()) {
final FileDialog fileDialog = new FileDialog(frame);
fileDialog.setMode(FileDialog.SAVE);
fileDialog.setDirectory(ClientContext.folderSettings().getSaveGamePath());
fileDialog.setFilenameFilter(( dir, name) -> {
// the extension should be .tsvg, but find svg extensions as well
return name.endsWith(".tsvg") || name.endsWith(".svg");
});
fileDialog.setVisible(true);
String fileName = fileDialog.getFile();
final String dirName = fileDialog.getDirectory();
if (fileName == null) {
return null;
} else {
if (!fileName.endsWith(".tsvg")) {
fileName += ".tsvg";
}
// If the user selects a filename that already exists,
// the AWT Dialog on Mac OS X will ask the user for confirmation
final File f = new File(dirName, fileName);
return f;
}
} else {
// Non-Mac platforms should use the normal Swing JFileChooser
final JFileChooser fileChooser = SaveGameFileChooser.getInstance();
final int rVal = fileChooser.showSaveDialog(frame);
if (rVal != JFileChooser.APPROVE_OPTION) {
return null;
}
File f = fileChooser.getSelectedFile();
// disallow sub directories to be entered (in the form directory/name) for Windows boxes
if (SystemProperties.isWindows()) {
final int slashIndex = Math.min(f.getPath().lastIndexOf("\\"), f.getPath().length());
final String filePath = f.getPath().substring(0, slashIndex);
if (!fileChooser.getCurrentDirectory().toString().equals(filePath)) {
JOptionPane.showConfirmDialog(frame, "Sub directories are not allowed in the file name. Please rename it.", "Cancel?", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
return null;
}
}
if (!f.getName().toLowerCase().endsWith(".tsvg")) {
f = new File(f.getParent(), f.getName() + ".tsvg");
}
// A small warning so users will not over-write a file
if (f.exists()) {
final int choice = JOptionPane.showConfirmDialog(frame, "A file by that name already exists. Do you wish to over write it?", "Over-write?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (choice != JOptionPane.OK_OPTION) {
return null;
}
}
return f;
}
}Example 69
| Project: Wiring-master File: Archiver.java View source code |
public void run() {
Sketch sketch = editor.getSketch();
// first save the sketch so that things don't archive strangely
boolean success = false;
try {
success = sketch.save();
} catch (Exception e) {
e.printStackTrace();
}
if (!success) {
Base.showWarning("Couldn't archive sketch", "Archiving the sketch has been canceled because\n" + "the sketch couldn't save properly.", null);
return;
}
File location = sketch.getFolder();
String name = location.getName();
File parent = new File(location.getParent());
//System.out.println("loc " + location);
//System.out.println("par " + parent);
File newbie = null;
String namely = null;
int index = 0;
do {
// only use the date if the sketch name isn't the default name
useDate = !name.startsWith("sketch_");
if (useDate) {
String purty = dateFormat.format(new Date());
String stamp = purty + ((char) ('a' + index));
namely = name + "-" + stamp;
newbie = new File(parent, namely + ".zip");
} else {
String diggie = numberFormat.format(index + 1);
namely = name + "-" + diggie;
newbie = new File(parent, namely + ".zip");
}
index++;
} while (newbie.exists());
// open up a prompt for where to save this fella
FileDialog fd = new FileDialog(editor, "Archive sketch as:", FileDialog.SAVE);
fd.setDirectory(parent.getAbsolutePath());
fd.setFile(newbie.getName());
fd.setVisible(true);
String directory = fd.getDirectory();
String filename = fd.getFile();
// only write the file if not canceled
if (filename != null) {
newbie = new File(directory, filename);
try {
//System.out.println(newbie);
FileOutputStream zipOutputFile = new FileOutputStream(newbie);
ZipOutputStream zos = new ZipOutputStream(zipOutputFile);
// recursively fill the zip file
buildZip(location, name, zos);
// close up the jar file
zos.flush();
zos.close();
editor.statusNotice("Created archive " + newbie.getName() + ".");
} catch (IOException e) {
e.printStackTrace();
}
} else {
editor.statusNotice("Archive sketch canceled.");
}
}Example 70
| Project: vassal-master File: FileChooser.java View source code |
protected FileDialog awt_file_dialog_init(Component parent) { final FileDialog fd; if (parent == null) { if (isJava15) { // Parentless Dialogs throw IllegalArgumentException with Java 1.5. fd = new FileDialog(dummy, title); } else { fd = new FileDialog((Frame) null, title); } } else if (parent instanceof Dialog) { fd = new FileDialog((Dialog) parent, title); } else if (parent instanceof Frame) { fd = new FileDialog((Frame) parent, title); } else { final Dialog d = (Dialog) SwingUtilities.getAncestorOfClass(Dialog.class, parent); if (d != null) { fd = new FileDialog(d, title); } else { final Frame f = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent); if (f != null) { fd = new FileDialog(f, title); } else { // should be impossible, parent is not in a dialog or frame! throw new IllegalArgumentException("parent is contained in neither a Dialog nor a Frame"); } } } fd.setModal(true); fd.setFilenameFilter(filter); if (cur != null) { if (cur.isDirectory()) fd.setDirectory(cur.getPath()); else { fd.setDirectory(cur.getParent()); fd.setFile(cur.getName()); } } return fd; }
Example 71
| Project: binnavi-master File: CFileChooser.java View source code |
private static int showNativeFileDialog(final JFileChooser chooser) {
final FileDialog result = new FileDialog((Frame) chooser.getParent());
result.setDirectory(chooser.getCurrentDirectory().getPath());
final File selected = chooser.getSelectedFile();
result.setFile(selected == null ? "" : selected.getPath());
result.setFilenameFilter(new FilenameFilter() {
@Override
public boolean accept(final File dir, final String name) {
return chooser.getFileFilter().accept(new File(dir.getPath() + File.pathSeparator + name));
}
});
if (chooser.getDialogType() == SAVE_DIALOG) {
result.setMode(FileDialog.SAVE);
} else {
// The native dialog only support Open and Save
result.setMode(FileDialog.LOAD);
}
if (chooser.getFileSelectionMode() == DIRECTORIES_ONLY) {
System.setProperty("apple.awt.fileDialogForDirectories", "true");
}
// Display dialog
result.setVisible(true);
System.setProperty("apple.awt.fileDialogForDirectories", "false");
if (result.getFile() == null) {
return CANCEL_OPTION;
}
final String selectedDir = result.getDirectory();
chooser.setSelectedFile(new File(FileUtils.ensureTrailingSlash(selectedDir) + result.getFile()));
return APPROVE_OPTION;
}Example 72
| Project: GogoMonkeyRun-master File: DialogBuilder.java View source code |
public static void showSettingSDKPathDialog(Component parentComponent) {
JOptionPane.showMessageDialog(parentComponent, R.string.dialog_alert_lack_of_sdk);
if (SystemUtils.isMac()) {
System.setProperty("apple.awt.fileDialogForDirectories", "true");
FileDialog dirChooser = new FileDialog((JFrame) parentComponent);
dirChooser.setDirectory(new File("/Applications").getAbsolutePath());
dirChooser.setLocation(50, 50);
dirChooser.setVisible(true);
String fileDir = null;
if (dirChooser.getFile() != null) {
String dir = dirChooser.getDirectory();
if (dir.endsWith(File.separator)) {
fileDir = dirChooser.getDirectory() + dirChooser.getFile();
} else {
fileDir = dirChooser.getDirectory() + File.separator + dirChooser.getFile();
}
}
if (fileDir != null)
PropertyUtils.saveProperty("sdk_path", fileDir);
System.setProperty("apple.awt.fileDialogForDirectories", "false");
} else {
JFileChooser dirChooser = new JFileChooser();
dirChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// disable the "All files" option.
dirChooser.setAcceptAllFileFilterUsed(false);
// 決定檔案儲å˜è·¯å¾‘
String fileDir = null;
dirChooser.setDialogTitle(R.string.dialog_title_choose_sdk);
if (dirChooser.showOpenDialog(parentComponent) == JFileChooser.APPROVE_OPTION) {
fileDir = dirChooser.getSelectedFile().getAbsolutePath();
}
if (fileDir != null)
PropertyUtils.saveProperty("sdk_path", fileDir);
}
}Example 73
| Project: JamVM-PH-master File: GtkFileDialogPeer.java View source code |
public void create() {
create((GtkContainerPeer) awtComponent.getParent().getPeer(), ((FileDialog) awtComponent).getMode());
FileDialog fd = (FileDialog) awtComponent;
nativeSetDirectory(System.getProperty("user.dir"));
setDirectory(fd.getDirectory());
setFile(fd.getFile());
FilenameFilter filter = fd.getFilenameFilter();
if (filter != null)
setFilenameFilter(filter);
}Example 74
| Project: jMathLib-master File: update.java View source code |
public OperandToken evaluate(Token[] operands, GlobalValues globals) {
String lineFile = "";
boolean successB = true;
globals.getInterpreter().displayText("UPDATING JMathLib\n");
// get update site of jmathlib
String updateSiteS = globals.getProperty("update.site.primary");
globals.getInterpreter().displayText("update site: " + updateSiteS);
// get local version of jmathlib
String localVersionS = globals.getProperty("jmathlib.version");
globals.getInterpreter().displayText("current version: " + localVersionS);
// first check to which version an update is possible
globals.getInterpreter().displayText("Checking to which version an update is possible");
// url of the update site including the request for the version to update to
URL url = null;
try {
url = new URL(updateSiteS + "?jmathlib_version=" + localVersionS + "&command=update");
} catch (Exception e) {
throwMathLibException("update: malformed url for getting update version");
successB = false;
}
// load information from the update server
Properties props = new Properties();
try {
props.load(url.openStream());
} catch (Exception e) {
System.out.println("updates: Properties error");
successB = false;
}
// Check return properties for "update-to-version"
// Update site could send a lot of properties
String updateVersionS = props.getProperty("update.toversion");
String updateActionS = props.getProperty("update.action");
// reaction on the response from the update server
if (updateActionS.equals("VERSION_UNKNOWN")) {
// the server does not recognize the local version of JMathLib
globals.getInterpreter().displayText("Your version of JMathLib is not known by the update server.");
return null;
} else if (updateVersionS.equals("NO_UPDATE_AVAILABLE") || updateActionS.equals("NO_ACTION")) {
// there is no update available on the server
globals.getInterpreter().displayText("No update available right now.");
return null;
} else if (updateActionS.equals("FULL_DOWNLOAD_REQUIRED")) {
// the updates requires to do a full download of a new version of JMathLib
globals.getInterpreter().displayText("\n");
globals.getInterpreter().displayText("Full download required in order to update!");
globals.getInterpreter().displayText("Please visit www.jmathlib.de for details.");
globals.getInterpreter().displayText("\n");
String urlS = props.getProperty("update.full_file_url");
String fileS = props.getProperty("update.file_name");
globals.getInterpreter().displayText("url: " + urlS);
globals.getInterpreter().displayText("file: " + fileS);
if ((urlS == null) || (fileS == null))
return null;
// open a file dialog to choose the download directory and download filename
Frame f = new Frame();
FileDialog theFileDialog = new FileDialog(f, "Save to ...", FileDialog.SAVE);
theFileDialog.setFile(fileS);
theFileDialog.setVisible(true);
String downloadDirS = theFileDialog.getDirectory();
fileS = theFileDialog.getFile();
if (downloadDirS == null)
throwMathLibException("download directory error");
if (fileS == null)
throwMathLibException("download file error");
globals.getInterpreter().setStatusText("You selected " + downloadDirS + " as download directory.");
// open URL to file on update server
try {
globals.getInterpreter().displayText("Downloading ... (please wait some minutes)");
URL fileURL = new URL(urlS);
InputStream in = fileURL.openStream();
// open file on local disc and download the new version of JMathLib
File file = new File(downloadDirS, fileS);
OutputStream out = new FileOutputStream(file);
byte[] cbuf = new byte[4096];
int len = -1;
int x = 0;
while ((len = in.read(cbuf)) != -1) {
out.write(cbuf, 0, len);
x += len;
globals.getInterpreter().setStatusText("downloaded " + new Integer(x).toString() + " bytes");
}
in.close();
out.close();
globals.getInterpreter().setStatusText("Downloading done.");
} catch (Exception e) {
successB = false;
globals.getInterpreter().displayText("update: problem downloading " + fileS);
}
// run the downloaded file
try {
globals.getInterpreter().displayText("Running installer ...");
Runtime.getRuntime().exec(downloadDirS + fileS);
globals.getInterpreter().displayText("Please exit JMathLib");
} catch (IOException exception) {
throwMathLibException("SystemCommand");
}
return null;
} else if (updateActionS.equals("INCREMENTAL_DOWNLOAD")) {
globals.getInterpreter().displayText("updating to version >" + updateVersionS + "< \n");
// download new files from server
updateSiteS += "jmathlib_" + updateVersionS + "/";
try {
url = new URL(updateSiteS);
} catch (Exception e) {
throwMathLibException("update: malformed url");
successB = false;
}
try {
BufferedReader inR = new BufferedReader(new InputStreamReader(url.openStream()));
String s = null;
// read next line from server
while ((s = inR.readLine()) != null) {
if (s.startsWith("file")) {
// read a file from the server and place it on the local disc
String fileS = s.substring(5).trim();
globals.getInterpreter().displayText("new file: >" + fileS + "<");
// open URL to file on update server
try {
URL fileURL = new URL(updateSiteS + fileS);
InputStream in = fileURL.openStream();
// open file on local disc
File file = new File(globals.getWorkingDirectory(), fileS);
OutputStream out = new FileOutputStream(file);
byte[] cbuf = new byte[4096];
int len = -1;
while ((len = in.read(cbuf)) != -1) {
out.write(cbuf, 0, len);
}
in.close();
out.close();
} catch (Exception e) {
successB = false;
globals.getInterpreter().displayText("update: problem downloading " + fileS);
}
} else if (s.startsWith("dir")) {
// create a directory on the local disc
String dirS = s.substring(4).trim();
globals.getInterpreter().displayText("new directory: >" + dirS + "<");
try {
File file = new File(globals.getWorkingDirectory(), dirS);
file.mkdir();
} catch (Exception e) {
successB = false;
globals.getInterpreter().displayText("update: problem creating directory " + dirS);
}
} else if (s.startsWith("del")) {
// delete a file/directory on the local disc
String delS = s.substring(4).trim();
globals.getInterpreter().displayText("delete file/dir: >" + delS + "<");
try {
File file = new File(globals.getWorkingDirectory(), delS);
file.delete();
} catch (Exception e) {
successB = false;
globals.getInterpreter().displayText("update: problem deleting " + delS);
}
} else if (s.startsWith("prop")) {
// delete a file/directory on the local disc
String propS = s.substring(5).trim();
globals.getInterpreter().displayText("new property: >" + propS + "<");
String[] p = propS.split("=");
globals.setProperty(p[0], p[1]);
} else {
// empty line or unknown command or comment
}
// in case something went wrong terminate
if (!successB)
break;
}
} catch (Exception e) {
throwMathLibException("update: open or reading stream");
}
} else {
throwMathLibException("update: unknown action");
}
// notifiy user
if (!successB)
globals.getInterpreter().displayText("\n Update was not successful. Repeat again later on or inform the admin.");
return null;
}Example 75
| Project: jopenray-master File: RecordingFrame.java View source code |
// // Let the user choose a file name showing a FileDialog. // protected boolean browseFile() { File currentFile = new File(fnameField.getText()); FileDialog fd = new FileDialog(this, "Save next session as...", FileDialog.SAVE); fd.setDirectory(currentFile.getParent()); fd.setVisible(true); if (fd.getFile() != null) { String newDir = fd.getDirectory(); String sep = System.getProperty("file.separator"); if (newDir.length() > 0) { if (!sep.equals(newDir.substring(newDir.length() - sep.length()))) newDir += sep; } String newFname = newDir + fd.getFile(); if (newFname.equals(fnameField.getText())) { fnameField.setText(newFname); return true; } } return false; }
Example 76
| Project: libreveris-master File: UIUtil.java View source code |
//-------------//
// fileChooser //
//-------------//
/**
* A replacement for standard JFileChooser, to allow better
* look & feel on the Mac platform.
*
* @param save true for a SAVE dialog, false for a LOAD dialog
* @param parent the parent component for the dialog
* @param startFile default file, or just default directory, or null
* @param filter a filter to by applied on files
* @return the selected file, or null
*/
public static File fileChooser(boolean save, Component parent, File startFile, OmrFileFilter filter) {
File file = null;
if (WellKnowns.MAC_OS_X) {
if ((parent == null) && (omr.Main.getGui() != null)) {
parent = omr.Main.getGui().getFrame();
}
Component parentFrame = parent;
while (!(parentFrame instanceof Frame) && (parentFrame.getParent() != null)) {
parentFrame = parentFrame.getParent();
}
try {
final FileDialog fd = new FileDialog((Frame) parentFrame);
if (startFile != null) {
fd.setDirectory(startFile.isDirectory() ? startFile.getPath() : startFile.getParent());
}
fd.setMode(save ? FileDialog.SAVE : FileDialog.LOAD);
fd.setFilenameFilter(filter);
String title = save ? "Saving: " : "Loading: ";
title += filter.getDescription();
fd.setTitle(title);
fd.setVisible(true);
String fileName = fd.getFile();
String dir = fd.getDirectory();
if ((dir != null) && (fileName != null)) {
String fullName = dir + WellKnowns.FILE_SEPARATOR + fileName;
file = new File(fullName);
}
} catch (ClassCastException e) {
logger.warn("no ancestor is Frame");
}
} else {
///final JFileChooser fc = new JFileChooser();
// see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6317789
final JFileChooser fc = new JFileChooser() {
@Override
public void updateUI() {
putClientProperty("FileChooser.useShellFolder", false);
super.updateUI();
}
};
// Pre-select the directory, and potentially the file to save to
if (startFile != null) {
if (startFile.isDirectory()) {
fc.setCurrentDirectory(startFile);
} else {
File parentFile = startFile.getParentFile();
fc.setCurrentDirectory(parentFile);
fc.setSelectedFile(startFile);
}
}
fc.addChoosableFileFilter(filter);
int result = save ? fc.showSaveDialog(parent) : fc.showOpenDialog(parent);
if (result == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
}
}
return file;
}Example 77
| Project: Mason-master File: JungDisplay.java View source code |
public void takeSnapshot() {
if (SimApplet.isApplet) {
Object[] options = { "Oops" };
JOptionPane.showOptionDialog(this, "You cannot save snapshots from an applet.", "MASON Applet Restriction", JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]);
return;
}
int width = viewer.getSize().width;
System.out.println(width);
int height = viewer.getSize().height;
Color bg = getBackground();
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics2D graphics = bi.createGraphics();
graphics.setColor(bg);
graphics.fillRect(0, 0, width, height);
viewer.paint(graphics);
// NOW pop up the save window
FileDialog fd = new FileDialog(this.frame, "Save Snapshot as 24-bit PNG...", FileDialog.SAVE);
fd.setFile("Untitled.png");
fd.setVisible(true);
if (fd.getFile() != null)
try {
OutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(fd.getDirectory(), Utilities.ensureFileEndsWith(fd.getFile(), ".png"))));
PngEncoder tmpEncoder = new PngEncoder(bi, false, PngEncoder.FILTER_NONE, 9);
stream.write(tmpEncoder.pngEncode());
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}Example 78
| Project: OOjDREW-master File: TypeDefFrame.java View source code |
/**
* This method prompts the user to select a file and then,
* places its contents in the typedef text area.
*/
public static void openFile() {
Frame parent = new Frame();
FileDialog fd = new FileDialog(parent, "Please choose a file:", FileDialog.LOAD);
fd.show();
String selectedItem = fd.getFile();
String fileName = fd.getDirectory() + fd.getFile();
try {
FileReader inFile = new FileReader(fileName);
BufferedReader in = new BufferedReader(inFile);
String read = "";
String contents = "";
while ((read = in.readLine()) != null) {
contents = contents + read + '\n';
}
in.close();
typetext.setText(contents);
} catch (Exception e) {
System.out.println(e.toString());
}
}Example 79
| Project: pdf2table-master File: MainFrame.java View source code |
private void browse1ActionPerformed(java.awt.event.ActionEvent evt) {
Frame f0 = new Frame();
try {
FileDialog file_dialog = new FileDialog(f0, "Source File");
file_dialog.setDirectory("C:");
file_dialog.setVisible(true);
String file_name = file_dialog.getFile();
String file_directory = file_dialog.getDirectory();
String target_file;
if (file_name.endsWith(".pdf")) {
int i = file_name.indexOf(".pdf");
target_file = file_name.substring(0, i);
this.f_name = target_file;
this.tf2.setText(file_directory + target_file);
String path = file_directory + file_name;
this.tf1.setText(path);
} else {
Dialog d = new Dialog(this, "Error", true);
d.add("Center", new Label("The source file must be a PDF file (example.pdf)!"));
Button b = new Button("Ok");
b.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button b2 = (Button) evt.getSource();
((Dialog) b2.getParent()).dispose();
}
});
d.setSize(200, 100);
d.add("South", b);
d.setLocationRelativeTo(null);
d.setVisible(true);
}
} catch (NullPointerException npe) {
System.out.println("Exception in class: user_interface and method: browse1. " + npe);
} catch (Exception e) {
System.out.println("Exception in class: user_interface and method: browse1. " + e);
}
}Example 80
| Project: phylowidget-master File: RenderOutput.java View source code |
public static synchronized void savePDF(PApplet p, BasicTreeRenderer r, boolean zoomToFull, boolean showAllLabels) {
PWContext context = PWPlatform.getInstance().getThisAppContext();
isOutputting = true;
RootedTree t = r.getTree();
float oldThreshold = context.config().renderThreshold;
context.config().renderThreshold = Integer.MAX_VALUE;
boolean oldDoubleBuff = context.config().useDoubleBuffering;
context.config().useDoubleBuffering = false;
float oldTextSize = context.config().minTextSize;
if (showAllLabels)
context.config().minTextSize = 0;
try {
context.getPW().setMessage("Outputting PDF...");
preprocess(t);
// File f = p.outputFile("Save PDF as...");
// String s = p.selectOutput("Save PDF as...");
String fileType = "PDF";
FileDialog fd = new FileDialog(context.ui().getFrame(), "Choose your desination " + fileType + " file.", FileDialog.SAVE);
fd.pack();
fd.setVisible(true);
String directory = fd.getDirectory();
String filename = fd.getFile();
if (filename == null) {
context.getPW().setMessage("Output cancelled.");
return;
}
// Fix a non-PDF extension.
if (!filename.toLowerCase().endsWith((".pdf"))) {
filename += ".pdf";
}
File f = new File(directory, filename);
p.noLoop();
PGraphics canvas = p.createGraphics(p.width, p.height, PConstants.PDF);
canvas.setPath(f.getAbsolutePath());
canvas.setSize(p.width, p.height);
canvas.beginDraw();
if (context.config().debug)
System.out.println("BEGIN DRAW");
/*
* Create the render rectangle.
*/
Rectangle2D.Float rect = TreeManager.cameraRect;
Rectangle2D.Float oldRect = rect;
if (zoomToFull) {
TreeManager.camera.fillScreen(0.5f);
TreeManager.camera.fforward();
context.trees().update();
rect = TreeManager.cameraRect;
}
/*
* Do the rendering!
*/
r.render(canvas, rect.x, rect.y, rect.width, rect.height, true);
if (context.config().debug)
System.out.println("END DRAW");
canvas.endDraw();
canvas.dispose();
context.getPW().setMessage("Output complete.");
} catch (Exception e) {
e.printStackTrace();
context.getPW().setMessage("PDF output failed: " + e.getMessage());
} finally {
context.config().renderThreshold = oldThreshold;
context.config().minTextSize = oldTextSize;
context.config().useDoubleBuffering = oldDoubleBuff;
isOutputting = false;
p.loop();
}
}Example 81
| Project: process-master File: Chooser.java View source code |
protected static void selectImpl(final Frame parentFrame, final String prompt, final File defaultSelection, final Callback callback, final int mode) {
// EventQueue.invokeLater(new Runnable() {
// public void run() {
File selectedFile = null;
if (useNativeSelect) {
FileDialog dialog = new FileDialog(parentFrame, prompt, mode);
if (defaultSelection != null) {
dialog.setDirectory(defaultSelection.getParent());
dialog.setFile(defaultSelection.getName());
}
dialog.setVisible(true);
String directory = dialog.getDirectory();
String filename = dialog.getFile();
if (filename != null) {
selectedFile = new File(directory, filename);
}
} else {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle(prompt);
if (defaultSelection != null) {
chooser.setSelectedFile(defaultSelection);
}
int result = -1;
if (mode == FileDialog.SAVE) {
result = chooser.showSaveDialog(parentFrame);
} else if (mode == FileDialog.LOAD) {
result = chooser.showOpenDialog(parentFrame);
}
if (result == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
}
}
//selectCallback(selectedFile, callbackMethod, callbackObject);
callback.handle(selectedFile);
// }
// });
}Example 82
| Project: processing-master File: Chooser.java View source code |
protected static void selectImpl(final Frame parentFrame, final String prompt, final File defaultSelection, final Callback callback, final int mode) {
// EventQueue.invokeLater(new Runnable() {
// public void run() {
File selectedFile = null;
if (useNativeSelect) {
FileDialog dialog = new FileDialog(parentFrame, prompt, mode);
if (defaultSelection != null) {
dialog.setDirectory(defaultSelection.getParent());
dialog.setFile(defaultSelection.getName());
}
dialog.setVisible(true);
String directory = dialog.getDirectory();
String filename = dialog.getFile();
if (filename != null) {
selectedFile = new File(directory, filename);
}
} else {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle(prompt);
if (defaultSelection != null) {
chooser.setSelectedFile(defaultSelection);
}
int result = -1;
if (mode == FileDialog.SAVE) {
result = chooser.showSaveDialog(parentFrame);
} else if (mode == FileDialog.LOAD) {
result = chooser.showOpenDialog(parentFrame);
}
if (result == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
}
}
//selectCallback(selectedFile, callbackMethod, callbackObject);
callback.handle(selectedFile);
// }
// });
}Example 83
| Project: VisiCut-master File: SelectThumbnailButton.java View source code |
public void actionPerformed(ActionEvent ae) {
if (Helper.isMacOS()) {
FileDialog fd = new FileDialog((Frame) null, java.util.ResourceBundle.getBundle("com/t_oster/uicomponents/resources/SelectThumbnailButton").getString("PLEASE SELECT A THUMBNAIL"));
fd.setMode(FileDialog.LOAD);
fd.setFilenameFilter(new FilenameFilter() {
public boolean accept(File file, String string) {
return string.toLowerCase().endsWith("png");
}
});
if (getDefaultDirectory() != null) {
fd.setDirectory(getDefaultDirectory().getAbsolutePath());
}
if (getThumbnailPath() != null) {
File tb = new File(getThumbnailPath());
fd.setDirectory(tb.getParent());
fd.setFile(tb.getName());
}
fd.setVisible(true);
if (fd.getFile() != null) {
File tb = new File(fd.getDirectory(), fd.getFile());
setThumbnailPath(tb.getAbsolutePath());
}
} else {
JFileChooser fc = new JFileChooser();
fc.setAcceptAllFileFilterUsed(false);
fc.addChoosableFileFilter(new ExtensionFilter(".png", java.util.ResourceBundle.getBundle("com/t_oster/uicomponents/resources/SelectThumbnailButton").getString("PNG FILES (*.PNG)")));
if (getDefaultDirectory() != null) {
fc.setCurrentDirectory(getDefaultDirectory());
}
if (getThumbnailPath() != null) {
fc.setSelectedFile(new File(getThumbnailPath()));
fc.setCurrentDirectory(new File(getThumbnailPath()).getParentFile());
}
fc.setDialogType(JFileChooser.OPEN_DIALOG);
if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
File thumb = fc.getSelectedFile();
setThumbnailPath(thumb.getPath());
}
}
}Example 84
| Project: filebot-master File: UserFiles.java View source code |
@Override
public List<File> showLoadDialogSelectFiles(boolean folderMode, boolean multiSelection, File defaultFile, ExtensionFileFilter filter, String title, ActionEvent evt) {
FileDialog fileDialog = createFileDialog(evt, title, FileDialog.LOAD, folderMode);
fileDialog.setTitle(title);
fileDialog.setMultipleMode(multiSelection);
if (defaultFile != null) {
if (folderMode && defaultFile.isDirectory()) {
fileDialog.setDirectory(defaultFile.getPath());
} else if (defaultFile.getParentFile() != null && defaultFile.getParentFile().isDirectory()) {
fileDialog.setDirectory(defaultFile.getParentFile().getPath());
fileDialog.setFile(defaultFile.getName());
}
}
if (filter != null) {
fileDialog.setFilenameFilter(filter);
}
fileDialog.setVisible(true);
return asList(fileDialog.getFiles());
}Example 85
| Project: FScape-master File: SelectPathButton.java View source code |
protected void showFileChooser() {
File p;
FileDialog fDlg;
// , fPath;
String fDir, fFile;
// int i;
Component win;
for (win = this; !(win instanceof Frame); ) {
win = SwingUtilities.getWindowAncestor(win);
if (win == null)
return;
}
p = getPath();
switch(type & PathField.TYPE_BASICMASK) {
case PathField.TYPE_INPUTFILE:
fDlg = new FileDialog((Frame) win, dlgTxt, FileDialog.LOAD);
break;
case PathField.TYPE_OUTPUTFILE:
fDlg = new FileDialog((Frame) win, dlgTxt, FileDialog.SAVE);
break;
case PathField.TYPE_FOLDER:
fDlg = new FileDialog((Frame) win, dlgTxt, FileDialog.SAVE);
// fDlg = new FolderDialog( (Frame) win, dlgTxt );
break;
default:
fDlg = null;
assert false : (type & PathField.TYPE_BASICMASK);
break;
}
if (p != null) {
fDlg.setFile(p.getName());
fDlg.setDirectory(p.getParent());
}
if (filter != null) {
fDlg.setFilenameFilter(filter);
}
showDialog(fDlg);
fDir = fDlg.getDirectory();
fFile = fDlg.getFile();
if (((type & PathField.TYPE_BASICMASK) != PathField.TYPE_FOLDER) && (fDir == null)) {
fDir = "";
}
if ((fFile != null) && (fDir != null)) {
if ((type & PathField.TYPE_BASICMASK) == PathField.TYPE_FOLDER) {
p = new File(fDir);
} else {
p = new File(fDir + fFile);
}
setPathAndDispatchEvent(p);
}
fDlg.dispose();
}Example 86
| Project: funCKit-master File: FunckitFileChooser.java View source code |
private File[] openDialog(Mode mode, String path) {
if (!nativeDialog) {
fileChooser.resetChoosableFileFilters();
}
if (path != null && !path.equals("")) {
File dir = new File(path);
if (nativeDialog) {
fileDialog.setDirectory(path);
} else {
fileChooser.setCurrentDirectory(dir);
}
}
String title = "";
switch(mode) {
case LOAD:
{
title = "FileDialog.open";
if (nativeDialog) {
fileDialog.setFilenameFilter(new LoadFilenameFilter());
} else {
fileChooser.addChoosableFileFilter(fckFormat);
fileChooser.addChoosableFileFilter(cmpFormat);
fileChooser.addChoosableFileFilter(sepFormat);
fileChooser.setFileFilter(fckFormat);
fileChooser.setMultiSelectionEnabled(true);
}
break;
}
case SAVE:
{
title = "FileDialog.save";
if (nativeDialog) {
fileDialog.setFilenameFilter(new SaveFilenameFilter());
} else {
fileChooser.addChoosableFileFilter(fckFormat);
fileChooser.addChoosableFileFilter(sepFormat);
fileChooser.addChoosableFileFilter(gifFormat);
fileChooser.addChoosableFileFilter(pdfFormat);
fileChooser.addChoosableFileFilter(pngFormat);
fileChooser.addChoosableFileFilter(svgFormat);
fileChooser.addChoosableFileFilter(jpgFormat);
fileChooser.setFileFilter(fckFormat);
}
break;
}
case SAVE_AS:
{
title = "FileDilaog.saveas";
if (nativeDialog) {
fileDialog.setFilenameFilter(new SaveFilenameFilter());
} else {
fileChooser.addChoosableFileFilter(fckFormat);
fileChooser.addChoosableFileFilter(sepFormat);
fileChooser.addChoosableFileFilter(gifFormat);
fileChooser.addChoosableFileFilter(pdfFormat);
fileChooser.addChoosableFileFilter(pngFormat);
fileChooser.addChoosableFileFilter(svgFormat);
fileChooser.addChoosableFileFilter(jpgFormat);
fileChooser.setFileFilter(fckFormat);
}
break;
}
case SAVE_COMPONENT:
{
title = "FileDialog.saveComponent";
if (nativeDialog) {
fileDialog.setFilenameFilter(new ComponentFileFilter());
} else {
fileChooser.addChoosableFileFilter(cmpFormat);
}
break;
}
}
if (nativeDialog) {
fileDialog.setMode(mode == Mode.LOAD ? FileDialog.LOAD : FileDialog.SAVE);
fileDialog.setTitle(Language.tr(title));
fileDialog.setVisible(true);
String fileName = fileDialog.getFile();
String directory = fileDialog.getDirectory();
if (fileName == null) {
return null;
}
File[] files = new File[1];
files[0] = new File(directory, fileName);
return files;
}
fileChooser.setDialogTitle(Language.tr(title));
int ret;
if (mode == Mode.LOAD) {
ret = fileChooser.showOpenDialog(view.getMainRootPane());
} else {
ret = fileChooser.showSaveDialog(view.getMainRootPane());
}
if (ret == JFileChooser.APPROVE_OPTION) {
if (fileChooser.getSelectedFiles().length == 0) {
File[] files = new File[1];
files[0] = fileChooser.getSelectedFile();
return files;
}
return fileChooser.getSelectedFiles();
}
return null;
}Example 87
| Project: GenPlay-master File: FileChooser.java View source code |
/**
* Opens a dialog box asking the user to choose a file or a directory to load or to save using a AWT component file chooser
* @param parentComponent determines the Frame in which the dialog is displayed; if null, or if the parentComponent has no Frame, a default Frame is used
* @param mode one of {@link #OPEN_FILE_MODE}, {@link #OPEN_DIRECTORY_MODE} or {@link #SAVE_FILE_MODE}
* @param choosableFileFilters {@link FileFilter} available
* @param selectedFile file preselected when the chooser pops up
* @return a file or a directory
*/
private static final File chooseFileUsingAWT(Component parentComponent, int mode, FileFilter[] choosableFileFilters, File selectedFile) {
if (mode == OPEN_DIRECTORY_MODE) {
System.setProperty("apple.awt.fileDialogForDirectories", "true");
}
Frame parentFrame = null;
if (parentComponent instanceof JComponent) {
JComponent jComponent = (JComponent) parentComponent;
if ((jComponent.getTopLevelAncestor() != null) && (jComponent.getTopLevelAncestor() instanceof Frame)) {
parentFrame = (Frame) jComponent.getTopLevelAncestor();
}
}
FileDialog fd = new FileDialog(parentFrame);
String defaultDirectory = ConfigurationManager.getInstance().getDefaultDirectory();
fd.setDirectory(defaultDirectory);
if (selectedFile != null) {
fd.setFile(selectedFile.getName());
}
if (mode == SAVE_FILE_MODE) {
fd.setMode(FileDialog.SAVE);
} else {
fd.setMode(FileDialog.LOAD);
}
if (mode == OPEN_DIRECTORY_MODE) {
// set file filter that only accepts directories
fd.setFilenameFilter(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return new File(dir, name).isDirectory();
}
});
} else if (choosableFileFilters != null) {
fd.setFilenameFilter(unionFilter(choosableFileFilters));
}
fd.setVisible(true);
if (mode == OPEN_DIRECTORY_MODE) {
System.setProperty("apple.awt.fileDialogForDirectories", "false");
}
if (fd.getFile() != null) {
return new File(fd.getDirectory(), fd.getFile());
} else {
return null;
}
}Example 88
| Project: i2b2-master File: rtest.java View source code |
public String rChooseFile(Rengine re, int newFile) {
FileDialog fd = new FileDialog(new Frame(), (newFile == 0) ? "Select a file" : "Select a new file", (newFile == 0) ? FileDialog.LOAD : FileDialog.SAVE);
fd.show();
String res = null;
if (fd.getDirectory() != null)
res = fd.getDirectory();
if (fd.getFile() != null)
res = (res == null) ? fd.getFile() : (res + fd.getFile());
return res;
}Example 89
| Project: jmodeltest2-master File: FramePreferences.java View source code |
private void exploreActionPerformed(java.awt.event.ActionEvent e) {
FileDialog dialog;
try {
try {
dialog = new FileDialog(this, "Select PhyML binaries directory", FileDialog.LOAD);
dialog.setDirectory(ModelTestConfiguration.DEFAULT_EXE_DIR);
dialog.setVisible(true);
} catch (Throwable f) {
f.printStackTrace();
return;
}
tfPathToPhyml.setText(dialog.getDirectory());
} catch (Exception f) {
f.printStackTrace();
}
}Example 90
| Project: JustWrite-master File: MainFrameController.java View source code |
public void doOpenFileAction() {
if (!okToAbandon()) {
return;
}
// show open file dialog; user selects file, or cancels
FileDialog fileDialog = new FileDialog(mainFrame, "Select a File to Open", FileDialog.LOAD);
if (lastDirectoryAccessed != null && !lastDirectoryAccessed.trim().equals("")) {
fileDialog.setDirectory(lastDirectoryAccessed);
}
fileDialog.setModal(true);
fileDialog.setVisible(true);
if (fileDialog.getFile() == null)
return;
// doesn't need a File.separator on Mac
lastDirectoryAccessed = fileDialog.getDirectory();
currentFilename = fileDialog.getDirectory() + fileDialog.getFile();
// if user did not cancel, get the file
loadFileContentsIntoEditorAndUpdateEverything(currentFilename);
}Example 91
| Project: kkMulticopterFlashTool-master File: MostRecentFileDialog.java View source code |
public int showOpenDialog(Component parent, String title) {
this.parent = parent;
this.title = title;
fileAccessMode = ACCESS_MODE_READ;
if (useSwingDialog()) {
JFileChooser fileChooser = new JFileChooser(getCurrentDirectory());
if (fileSelectionMode == DIRECTORIES_ONLY)
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
else if (extension != null)
fileChooser.setFileFilter(new FileNameFilter(extension));
int returnVal = fileChooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
setSelectedFile(fileChooser.getSelectedFile());
setCurrentDirectory(fileChooser.getCurrentDirectory());
return returnVal;
}
return returnVal;
} else {
if (parent == null)
parent = new Frame();
Frame frame = (Frame) SwingUtilities.getRoot(parent);
FileDialog dialog = new FileDialog(frame, "Open", FileDialog.LOAD);
if (extension != null) {
dialog.setFilenameFilter(new FileNameFilter(extension));
}
File currentDir = getCurrentDirectory();
String startingPath = ".";
if (currentDir != null) {
startingPath = currentDir.getAbsolutePath();
}
dialog.setDirectory(startingPath);
dialog.show();
// the docs for FileDialog.getDirectory say it can
// return null. This could happen if the directory
// set above is invalid (it has been deleted perhaps?)
String selectedDirectoryStr = dialog.getDirectory();
// Save the selected directory
File selectedDirectory = null;
if (selectedDirectoryStr != null) {
selectedDirectory = new File(selectedDirectoryStr);
setCurrentDirectory(selectedDirectory);
}
File selectedFile = null;
if (fileSelectionMode == DIRECTORIES_ONLY) {
if (selectedDirectory != null) {
selectedFile = selectedDirectory;
} else {
// we don't have a valid directory so I guess we
// set the selected File to null
// we don't need an if for this but it makes
// it more clear.
selectedFile = null;
}
} else {
String selectedFileStr = dialog.getFile();
// will be null
if (selectedFileStr != null) {
if (selectedDirectory != null) {
selectedFile = new File(selectedDirectory, selectedFileStr);
} else {
// we don't have a valid directory, but might have
// a valid file. I'll take a guess to great the file
// with the working direcotry
selectedFile = new File(selectedFileStr);
}
}
}
dialog.dispose();
if (selectedFile != null) {
setSelectedFile(selectedFile);
return APPROVE_OPTION;
}
return CANCEL_OPTION;
}
// return ERROR_OPTION;
}Example 92
| Project: mibble-master File: OpenDialog.java View source code |
/**
* Opens the MIB file dialog and returns its result for this
* dialog as well.
*/
protected void openFile() {
FileDialog dialog = new FileDialog(this, "Select MIB File");
dialog.setDirectory(lastDir);
dialog.setVisible(true);
if (dialog.getFile() != null) {
File file = new File(dialog.getDirectory(), dialog.getFile());
lastDir = dialog.getDirectory();
mibs = new String[] { file.getAbsolutePath() };
}
this.dispose();
}Example 93
| Project: nbt-master File: NBTViewer.java View source code |
private void openFile() {
FileDialog d = new FileDialog(this, "Open File", FileDialog.LOAD);
d.setVisible(true);
if (d.getDirectory() == null || d.getFile() == null) {
return;
}
File dir = new File(d.getDirectory());
File f = new File(dir, d.getFile());
List<Tag<?>> tags = readFile(f);
updateTree(tags);
top.setUserObject("NBT Contents [" + format + "]");
((DefaultTreeModel) tree.getModel()).nodeChanged(top);
}Example 94
| Project: opennars-master File: LogPanel.java View source code |
public boolean openLogFile() {
FileDialog dialog = new FileDialog((Dialog) null, "Inference Log", FileDialog.SAVE);
dialog.setVisible(true);
String directoryName = dialog.getDirectory();
logFilePath = dialog.getFile();
if (logFilePath == null) {
return false;
}
try {
boolean append = true;
boolean autoflush = true;
logFile = new PrintWriter(new FileWriter(directoryName + logFilePath, append), autoflush);
output(LOG.class, "Stream opened: " + logFilePath);
return true;
} catch (IOException ex) {
output(ERR.class, "Log file save: I/O error: " + ex.getMessage());
}
return false;
}Example 95
| Project: PyramidShader-master File: MainWindow.java View source code |
//GEN-LAST:event_savePlanObliqueMenuItemActionPerformed
/**
* Ask the user for a file to read or write.
*
* @param frame A Frame for which to display the dialog.
* @param message A message that will be displayed in the dialog.
* @param load Pass true if an existing file for reading should be selected.
* Pass false if a new file for writing should be specified.
* @return A path to the file, including the file name.
*/
private String askFile(String message, boolean load) {
int flag = load ? java.awt.FileDialog.LOAD : java.awt.FileDialog.SAVE;
// display the dialog
java.awt.FileDialog fd = new java.awt.FileDialog(this, message, flag);
fd.setVisible(true);
// construct the path to the file that the user selected.
String fileName = fd.getFile();
String directory = fd.getDirectory();
if (fileName == null || directory == null) {
return null;
}
return directory + fileName;
}Example 96
| Project: qvcsos-master File: DefineInputFilesDialog.java View source code |
@Override
public void actionPerformed(ActionEvent e) {
FileDialog getFileName = new FileDialog(parentFrame, "Select File 1");
getFileName.setMode(FileDialog.LOAD);
getFileName.setModal(true);
getFileName.setDirectory(dirNameFromFilename(m_FirstFileTextField.getText()));
getFileName.setVisible(true);
if (getFileName.getFile() != null) {
m_FirstFileTextField.setText(getFileName.getDirectory() + getFileName.getFile());
}
}Example 97
| Project: SPaTo_Visual_Explorer-master File: FileDialogUtils.java View source code |
public void run() {
File lastDir = new File(app.prefs.get("workspace.lastDirectory", ""));
if (lastDir.getAbsolutePath().equals(""))
lastDir = null;
if (app.platform == PApplet.MACOSX) {
// use FileDialog instead of JFileChooser as per Apple recommendation
FileDialog fd = new FileDialog(app.getParentFrame(), (title != null) ? title : (mode == SAVE) ? "Save..." : "Open...", (mode == SAVE) ? FileDialog.SAVE : FileDialog.LOAD);
fd.setFilenameFilter(new FilenameFileFilterAdapter(ff));
String dirname = null;
if (selectedFile != null)
dirname = selectedFile.getParent();
else if (lastDir != null)
dirname = lastDir.getAbsolutePath();
fd.setDirectory(dirname);
fd.setFile((selectedFile != null) ? selectedFile.getAbsolutePath() : null);
fd.setVisible(true);
selectFilesResult = new File[0];
if ((fd.getFile() != null) && ((mode == SAVE) || ff.accept(new File(fd.getDirectory(), fd.getFile()))))
selectFilesResult = new File[] { new File(fd.getDirectory(), fd.getFile()) };
} else {
JFileChooser fc = new JFileChooser();
// set initial directory and possibly initially selected file
fc.setCurrentDirectory((selectedFile != null) ? selectedFile.getParentFile() : lastDir);
if (selectedFile != null)
fc.setSelectedFile(selectedFile);
// setup dialog look and feel
fc.setDialogTitle((title != null) ? title : (mode == SAVE) ? "Save..." : "Open...");
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
// allow selecting multiple documents to load
fc.setMultiSelectionEnabled(mode == OPENMULTIPLE);
fc.setAcceptAllFileFilterUsed(ff == null);
if (ff != null)
fc.setFileFilter((app.platform == PApplet.WINDOWS) ? new WindowsFileFilterAdapter(ff) : ff);
// run dialog
if (fc.showDialog(app.getParentFrame(), (mode == SAVE) ? "Save" : "Open") == JFileChooser.APPROVE_OPTION) {
// save current directory to preferences
File dir = fc.getCurrentDirectory();
app.prefs.put("workspace.lastDirectory", (dir != null) ? dir.getAbsolutePath() : null);
// evaluate selection
File files[] = fc.isMultiSelectionEnabled() ? fc.getSelectedFiles() : new File[] { fc.getSelectedFile() };
if (mode != SAVE)
for (int i = 0; i < files.length; i++) if ((ff != null) && !ff.accept(files[i]))
files[i] = null;
// transcribe selection into result array
selectFilesResult = new File[0];
for (int i = 0; i < files.length; i++) if (files[i] != null)
selectFilesResult = (File[]) PApplet.append(selectFilesResult, files[i]);
}
}
}Example 98
| Project: alloy4smt-master File: OurDialog.java View source code |
/** Use the platform's preferred file chooser to ask the user to select a file.
* <br> Note: if it is a save operation, and the user didn't include an extension, then we'll add the extension.
* @param isOpen - true means this is an Open operation; false means this is a Save operation
* @param dir - the initial directory (or null if we want to use the default)
* @param ext - the file extension (including "."; using lowercase letters; for example, ".als") or ""
* @param description - the description for the given extension
* @return null if the user didn't choose anything, otherwise it returns the selected file
*/
public static File askFile(boolean isOpen, String dir, final String ext, final String description) {
if (dir == null)
dir = Util.getCurrentDirectory();
if (!(new File(dir).isDirectory()))
dir = System.getProperty("user.home");
dir = Util.canon(dir);
String ans;
if (useAWT) {
// this window is unused and not shown; needed by FileDialog and nothing more
Frame parent = new Frame("Alloy File Dialog");
FileDialog open = new FileDialog(parent, isOpen ? "Open..." : "Save...");
open.setAlwaysOnTop(true);
open.setMode(isOpen ? FileDialog.LOAD : FileDialog.SAVE);
open.setDirectory(dir);
if (ext.length() > 0)
open.setFilenameFilter(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase(Locale.US).endsWith(ext);
}
});
// This method blocks until the user either chooses something or cancels the dialog.
open.setVisible(true);
parent.dispose();
if (open.getFile() == null)
return null;
else
ans = open.getDirectory() + File.separatorChar + open.getFile();
} else {
try {
JFileChooser open = new JFileChooser(dir) {
private static final long serialVersionUID = 0;
public JDialog createDialog(Component parent) throws HeadlessException {
JDialog dialog = super.createDialog(null);
dialog.setAlwaysOnTop(true);
return dialog;
}
};
open.setDialogTitle(isOpen ? "Open..." : "Save...");
open.setApproveButtonText(isOpen ? "Open" : "Save");
open.setDialogType(isOpen ? JFileChooser.OPEN_DIALOG : JFileChooser.SAVE_DIALOG);
if (ext.length() > 0)
open.setFileFilter(new FileFilter() {
public boolean accept(File file) {
return !file.isFile() || file.getPath().toLowerCase(Locale.US).endsWith(ext);
}
public String getDescription() {
return description;
}
});
if (open.showDialog(null, null) != JFileChooser.APPROVE_OPTION || open.getSelectedFile() == null)
return null;
ans = open.getSelectedFile().getPath();
} catch (Exception ex) {
useAWT = true;
return askFile(isOpen, dir, ext, description);
}
}
if (!isOpen) {
int lastSlash = ans.lastIndexOf(File.separatorChar);
int lastDot = (lastSlash >= 0) ? ans.indexOf('.', lastSlash) : ans.indexOf('.');
if (lastDot < 0)
ans = ans + ext;
}
return new File(Util.canon(ans));
}Example 99
| Project: Electric-VLSI-master File: OpenFile.java View source code |
/**
* Factory method to create a new open dialog box using the default Type.
* @param type the type of file to read. Defaults to ANY if null.
* @param title dialog title to use; if null uses "Open 'filetype'".
* @param wantDirectory true to request a directory be selected, instead of a file.
* @param initialDir the initial directory
* @param setSelectedDirAsWorkingDir if the user approves the selection,
* set the directory as the current working dir if this is true.
*/
public static String chooseInputFile(FileType type, String title, boolean wantDirectory, String initialDir, boolean setSelectedDirAsWorkingDir) {
if (title == null) {
if (type != null) {
if (wantDirectory)
title = "Choose Directory with " + type.getDescription() + " files";
else
title = "Open " + type.getDescription();
} else {
if (wantDirectory)
title = "Choose Directory";
else
title = "Open file";
}
}
boolean useSwing = true;
// MacOS Open Dialog doesn't work when directories must be available for selection
// if (!wantDirectory && Client.isOSMac())
// useSwing = false;
// if (location == null) location = new Point(100, 50);
// System.out.println("Put it at "+location);
String path = (type != null) ? type.getGroupPath() : null;
if (path != null)
initialDir = path;
if (useSwing) {
OpenFileSwing dialog = new OpenFileSwing();
dialog.saveDialog = false;
dialog.setSelectedDirAsWorkingDir = setSelectedDirAsWorkingDir;
dialog.fileType = type;
dialog.setDialogTitle(title);
File dir = new File(initialDir);
if (!dir.exists() || !dir.isDirectory())
dir = new File(User.getWorkingDirectory());
dialog.setCurrentDirectory(dir);
if (type != null) {
if (type == FileType.ELIB || type == FileType.JELIB || type == FileType.DELIB || type == FileType.LIBFILE || type == FileType.LIBRARYFORMATS) {
LibDirs.LibDirFileSystemView view = LibDirs.newLibDirFileSystemView(dialog.getFileSystemView());
dialog.setFileSystemView(view);
dialog.setFileView(new LibDirs.LibDirFileView(view));
}
dialog.setFileFilter(type.getFileFilterSwing());
}
if (wantDirectory)
dialog.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// dialog.setLocation(location.x, location.y);
// dialog.addComponentListener(new MoveComponentListener());
JFrame chooseFrame = new JFrame();
chooseFrame.setIconImage((Image) Main.getFrameIcon());
int returnVal = dialog.showOpenDialog(chooseFrame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = dialog.getSelectedFile();
return file.getPath();
}
return null;
}
// the AWT way
FileDialog dialog = new FileDialog((Frame) Main.getCurrentJFrame(), title, FileDialog.LOAD);
dialog.setDirectory(User.getWorkingDirectory());
if (type != null)
dialog.setFilenameFilter(type.getFileFilterAWT());
dialog.setVisible(true);
String fileName = dialog.getFile();
if (fileName == null)
return null;
User.setWorkingDirectory(dialog.getDirectory());
return dialog.getDirectory() + fileName;
}Example 100
| Project: Electric8-master File: OpenFile.java View source code |
/**
* Factory method to create a new open dialog box using the default Type.
* @param type the type of file to read. Defaults to ANY if null.
* @param title dialog title to use; if null uses "Open 'filetype'".
* @param wantDirectory true to request a directory be selected, instead of a file.
* @param initialDir the initial directory
* @param setSelectedDirAsWorkingDir if the user approves the selection,
* set the directory as the current working dir if this is true.
*/
public static String chooseInputFile(FileType type, String title, boolean wantDirectory, String initialDir, boolean setSelectedDirAsWorkingDir) {
if (title == null) {
if (type != null) {
if (wantDirectory)
title = "Choose Directory with " + type.getDescription() + " files";
else
title = "Open " + type.getDescription();
} else {
if (wantDirectory)
title = "Choose Directory";
else
title = "Open file";
}
}
boolean useSwing = true;
// MacOS Open Dialog doesn't work when directories must be available for selection
// if (!wantDirectory && Client.isOSMac())
// useSwing = false;
// if (location == null) location = new Point(100, 50);
// System.out.println("Put it at "+location);
String path = (type != null) ? type.getGroupPath() : null;
if (path != null)
initialDir = path;
if (useSwing) {
OpenFileSwing dialog = new OpenFileSwing();
dialog.saveDialog = false;
dialog.setSelectedDirAsWorkingDir = setSelectedDirAsWorkingDir;
dialog.fileType = type;
dialog.setDialogTitle(title);
File dir = new File(initialDir);
if (!dir.exists() || !dir.isDirectory())
dir = new File(User.getWorkingDirectory());
dialog.setCurrentDirectory(dir);
if (type != null) {
if (type == FileType.ELIB || type == FileType.JELIB || type == FileType.DELIB || type == FileType.LIBFILE || type == FileType.LIBRARYFORMATS) {
LibDirs.LibDirFileSystemView view = LibDirs.newLibDirFileSystemView(dialog.getFileSystemView());
dialog.setFileSystemView(view);
dialog.setFileView(new LibDirs.LibDirFileView(view));
}
dialog.setFileFilter(type.getFileFilterSwing());
}
if (wantDirectory)
dialog.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// dialog.setLocation(location.x, location.y);
// dialog.addComponentListener(new MoveComponentListener());
JFrame chooseFrame = new JFrame();
//chooseFrame.setIconImage(Main.getFrameIcon().getImage()); TODO fix this
int returnVal = dialog.showOpenDialog(chooseFrame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = dialog.getSelectedFile();
return file.getPath();
}
return null;
}
// the AWT way
FileDialog dialog = new FileDialog(Main.getCurrentJFrame(), title, FileDialog.LOAD);
dialog.setDirectory(User.getWorkingDirectory());
if (type != null)
dialog.setFilenameFilter(type.getFileFilterAWT());
dialog.setVisible(true);
String fileName = dialog.getFile();
if (fileName == null)
return null;
User.setWorkingDirectory(dialog.getDirectory());
return dialog.getDirectory() + fileName;
}Example 101
| Project: fosstrak-fc-master File: AbstractTab.java View source code |
/**
* This method adds a choose file field to the panel.
*
* @param panel to which the choose file field should be added
*/
protected void addChooseFileField(JPanel panel) {
m_filePathField = new JTextField();
m_filePathField.setFont(m_font);
final FileDialog fileDialog = new FileDialog(m_parent);
fileDialog.setModal(true);
fileDialog.addComponentListener(new ComponentAdapter() {
public void componentHidden(ComponentEvent e) {
if (fileDialog.getFile() != null) {
m_filePathField.setText(fileDialog.getDirectory() + fileDialog.getFile());
}
}
});
final JButton chooseFileButton = new JButton(m_guiText.getString("ChooseFileButtonLabel"));
chooseFileButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fileDialog.setVisible(true);
}
});
chooseFileButton.setFont(m_font);
JLabel lbl = new JLabel(m_guiText.getString("FilePathLabel"));
lbl.setFont(m_font);
panel.add(lbl);
panel.add(m_filePathField);
panel.add(chooseFileButton);
}