下面列出了org.eclipse.swt.widgets.FileDialog#open ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static String openFileDialog(Shell shell, String extension,
String defaultName, String filterPath, int swtFlag) {
FileDialog dialog = new FileDialog(shell, swtFlag);
dialog.setText(getDialogText(swtFlag));
String ext = null;
if (extension != null) {
ext = extension.trim();
if (ext.contains("|"))
ext = ext.substring(0, ext.indexOf("|")).trim();
dialog.setFilterExtensions(new String[] { ext });
}
dialog.setFileName(defaultName);
if (filterPath != null)
dialog.setFilterPath(filterPath);
if (extension != null) {
if (extension.contains("|")) {
String label = extension.substring(extension.indexOf("|") + 1);
label += " (" + ext + ")";
dialog.setFilterNames(new String[] { label });
}
}
return dialog.open();
}
/**
* Open an appropriate destination browser so that the user can specify a source to import from
*/
protected void handleDestinationBrowseButtonPressed() {
FileDialog dialog = new FileDialog(getContainer().getShell(), SWT.SAVE | SWT.SHEET);
dialog.setFilterExtensions(new String[] { "*.hszip", "*" }); //$NON-NLS-1$ //$NON-NLS-2$
dialog.setText(DataTransferMessages.ArchiveExport_selectDestinationTitle);
String currentSourceString = getDestinationValue();
int lastSeparatorIndex = currentSourceString.lastIndexOf(File.separator);
if (lastSeparatorIndex != -1) {
dialog.setFilterPath(currentSourceString.substring(0, lastSeparatorIndex));
}
String selectedFileName = dialog.open();
if (selectedFileName != null) {
setErrorMessage(null);
setDestinationValue(selectedFileName);
if (getWhiteCheckedResources().size() > 0) {
setDescription(null);
}
}
}
public void choose(UIFileChooserHandler selectionHandler) {
FileDialog dialog = new FileDialog(this.window.getControl(), this.style);
if( this.text != null ) {
dialog.setText(this.text);
}
dialog.setFileName(this.createFileName());
dialog.setFilterPath(this.createFilterPath());
if( this.supportedFormats != null ) {
FilterList filter = new FilterList(this.supportedFormats);
dialog.setFilterNames(filter.getFilterNames());
dialog.setFilterExtensions(filter.getFilterExtensions());
}
String path = dialog.open();
selectionHandler.onSelectFile(path != null ? new File(path) : null);
}
public void sendFile() {
if (this.selectedPeer == null) return;
FileDialog fd = new FileDialog(shlSimpleChatExample, SWT.OPEN);
fd.setText("Choose a file to send");
String selected = fd.open();
if (selected == null) return;
Path path = FileSystems.getDefault().getPath(selected);
OpenOption[] read = { StandardOpenOption.READ };
try {
FileChannel fileChannel = FileChannel.open(path, read);
this.selectedPeer.sendFile(fileChannel, path.getFileName().toString(), (int)fileChannel.size());
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Opens a file chooser and gives the user an opportunity to save the chart
* in PNG format.
*
* @throws IOException if there is an I/O error.
*/
public void doSaveAs() throws IOException {
FileDialog fileDialog = new FileDialog(this.canvas.getShell(),
SWT.SAVE);
String[] extensions = {"*.png"};
fileDialog.setFilterExtensions(extensions);
String filename = fileDialog.open();
if (filename != null) {
if (isEnforceFileExtensions()) {
if (!filename.endsWith(".png")) {
filename = filename + ".png";
}
}
//TODO replace getSize by getBounds ?
ChartUtilities.saveChartAsPNG(new File(filename), this.chart,
this.canvas.getSize().x, this.canvas.getSize().y);
}
}
protected void handleAdd ()
{
final FileDialog dlg = new FileDialog ( getShell (), SWT.OPEN );
final String result = dlg.open ();
if ( result != null )
{
try
{
this.factory.addFile ( result );
}
catch ( final Exception e )
{
ErrorDialog.openError ( getShell (), "Error", "Failed to add file", StatusHelper.convertStatus ( Activator.PLUGIN_ID, e ) );
}
}
}
@Override
protected String handleBrowseButton() {
FileDialog dialog = new FileDialog(getShell(), SWT.OPEN);
String[] filterExtensions = editor.getInterpreterFilterExtensions();
if (filterExtensions != null) {
dialog.setFilterExtensions(filterExtensions);
}
String file = dialog.open();
return file;
}
public String saveFile()
{
FileDialog dlg = new FileDialog(button.getShell(), SWT.SAVE);
dlg.setFileName(text.getText());
dlg.setText(OK);
String path = dlg.open();
return path;
}
protected void handleFileBrowseButtonPressed(Text text, String[] extensions, String title) {
FileDialog dialog= new FileDialog(text.getShell());
dialog.setText(title);
dialog.setFilterExtensions(extensions);
String dirName= text.getText();
if (!dirName.equals("")) { //$NON-NLS-1$
File path= new File(dirName);
if (path.exists())
dialog.setFilterPath(dirName);
}
String selectedDirectory= dialog.open();
if (selectedDirectory != null)
text.setText(selectedDirectory);
}
public void run( )
{
Object selectedElement = ( (TreeItem) composite.getSelectedElement( ) ).getData( );
if ( selectedElement == null
|| !( selectedElement instanceof ReportDesignHandle ) )
{
return;
}
String filename = ( (ReportDesignHandle) selectedElement ).getFileName( );
String reportName = filename.substring( filename.lastIndexOf( "/" ) + 1 ); //$NON-NLS-1$
final FileDialog saveDialog = new FileDialog( composite.getShell( ),
SWT.SAVE );
saveDialog.setFilterExtensions( REPORTDESIGN_FILENAME_PATTERN );
saveDialog.setFileName( reportName );
if ( saveDialog.open( ) == null )
return;
PlaceResources.copy( composite.getShell( ),
saveDialog.getFilterPath( ),
saveDialog.getFileName( ),
filename );
PlaceResources.copyExcludedRptDesignes( composite.getShell( ),
saveDialog.getFilterPath( ),
filename,
true );
if ( ( (TreeItem) composite.getSelectedElement( ) ).getParentItem( )
.getText( )
.equals( DRILL_TO_DETAILS_CATEGORY ) )
{
PlaceResources.copyDrillThroughReport( composite.getShell( ),
saveDialog.getFilterPath( ),
reportName );
}
}
/**
* (non-Javadoc)
* @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
*/
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
final TmxEditorViewer tmxEditorViewer = TmxEditorViewer.getInstance();
if (tmxEditorViewer == null) {
OpenMessageUtils.openMessageWithReason(IStatus.ERROR,
Messages.getString("handler.OpenTmxFileHandler.openFileErrorMsg"),
Messages.getString("handler.OpenTmxFileHandler.cantFindEditorViewerMsg"));
return null;
}
FileDialog fileDialg = new FileDialog(Display.getDefault().getActiveShell());
fileDialg.setFilterExtensions(new String[] { "*.hstm", "*.*" });
String result = fileDialg.open();
if (result == null) {
return null;
}
File f = new File(result);
if (!f.exists()) {
return null;
}
// 修改当文件打开后关闭以前打开的文件
if (tmxEditorViewer.getTmxEditor() != null) {
if(!tmxEditorViewer.closeTmx()){
return null;
}
}
String path = f.getParent();
String name = f.getName();
final DatabaseModelBean selectedVal = new DatabaseModelBean();
selectedVal.setDbName(name);
selectedVal.setDbType(Constants.DBTYPE_SQLITE);
selectedVal.setItlDBLocation(path);
tmxEditorViewer.open(selectedVal);
return null;
}
@Override
public Object execute(final ExecutionEvent event) throws ExecutionException {
final FileDialog fd = new FileDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.OPEN | SWT.MULTI);
fd.setFilterExtensions(new String[] { "*.jar;*.zip" });
if (filenames != null) {
fd.setFilterNames(filenames);
}
if (fd.open() != null) {
final DependencyRepositoryStore libStore = RepositoryManager.getInstance().getRepositoryStore(DependencyRepositoryStore.class);
final String[] jars = fd.getFileNames();
final IProgressService progressManager = PlatformUI.getWorkbench().getProgressService();
final IRunnableWithProgress runnable = new ImportLibsOperation(libStore, jars, fd.getFilterPath());
try {
progressManager.run(true, false, runnable);
progressManager.run(true, false, new IRunnableWithProgress() {
@Override
public void run(final IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException {
RepositoryManager.getInstance().getCurrentRepository().build(monitor);
}
});
} catch (final InvocationTargetException e1) {
BonitaStudioLog.error(e1);
if (e1.getCause() != null && e1.getCause().getMessage() != null) {
MessageDialog.openError(Display.getDefault().getActiveShell(), org.bonitasoft.studio.dependencies.i18n.Messages.importJar, e1.getCause()
.getMessage());
}
} catch (final InterruptedException e2) {
BonitaStudioLog.error(e2);
}
}
return fd.getFileNames();
}
@Override
public void run() {
FileDialog dialog = new FileDialog(getViewSite().getShell(),
SWT.OPEN);
dialog.setFileName(lastSelection);
String[] filterSuffixPattern = new String[EXTENSIONS.length + 1];
String[] filterReadableName = new String[EXTENSIONS.length + 1];
filterSuffixPattern[0] = "*.*"; //$NON-NLS-1$
filterReadableName[0] = String.format("Embedded DOT Graph (%s)", //$NON-NLS-1$
filterSuffixPattern[0]);
for (int i = 1; i <= EXTENSIONS.length; i++) {
String suffix = EXTENSIONS[i - 1];
filterSuffixPattern[i] = "*." + suffix; //$NON-NLS-1$
filterReadableName[i] = String.format(Locale.ENGLISH,
"%S file (%s)", suffix, //$NON-NLS-1$
filterSuffixPattern[i]);
}
dialog.setFilterExtensions(filterSuffixPattern);
dialog.setFilterNames(filterReadableName);
String selection = dialog.open();
if (selection != null) {
lastSelection = selection;
updateGraph(new File(selection));
}
}
private void handleRequest(XMPPFileTransferRequest request) {
String filename = request.getFileName();
long fileSize = request.getFileSize();
if (!MessageDialog.openQuestion(
SWTUtils.getShell(),
"File Transfer Request",
request.getContact().getDisplayableName()
+ " wants to send a file."
+ "\nName: "
+ filename
+ "\nSize: "
+ CoreUtils.formatByte(fileSize)
+ (fileSize < 1000 ? "yte" : "")
+ "\n\nAccept the file?")) {
request.reject();
return;
}
FileDialog fd = new FileDialog(SWTUtils.getShell(), SWT.SAVE);
fd.setText(Messages.SendFileAction_filedialog_text);
fd.setOverwrite(true);
fd.setFileName(filename);
String destination = fd.open();
if (destination == null) {
request.reject();
return;
}
File file = new File(destination);
if (file.isDirectory()) {
request.reject();
return;
}
Job job = new IncomingFileTransferJob(request, file);
job.setUser(true);
job.schedule();
}
private File[] getFile(final File startingDirectory) {
int style = SWT.OPEN;
if (multiple) {
style |= SWT.MULTI;
}
final FileDialog dialog = new FileDialog(getShell(), style);
if (startingDirectory != null) {
dialog.setFileName(startingDirectory.getPath());
}
if (extensions != null) {
dialog.setFilterExtensions(extensions);
}
dialog.open();
final String[] fileNames = dialog.getFileNames();
if (fileNames.length > 0) {
final File[] files = new File[fileNames.length];
for (int i = 0; i < fileNames.length; i++) {
files[i] = new File(dialog.getFilterPath(), fileNames[i]);
}
return files;
}
return null;
}
private void saveResults() {
FileDialog fd = new FileDialog(getSite().getWorkbenchWindow().getShell(), SWT.SAVE);
fd.setText("Save Results");
String[] filterExt = { "*.txt" };
fd.setFilterExtensions(filterExt);
String selected = fd.open();
if(selected != null) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter(selected));
Tree tree = treeViewer.getTree();
/*TreeColumn[] columns = tree.getColumns();
for(int i=0; i<columns.length; i++) {
if(i == columns.length-1)
out.write(columns[i].getText());
else
out.write(columns[i].getText() + "\t");
}
out.newLine();*/
for(int i=0; i<tree.getItemCount(); i++) {
TreeItem treeItem = tree.getItem(i);
ExtractClassCandidateGroup group = (ExtractClassCandidateGroup)treeItem.getData();
for(CandidateRefactoring candidate : group.getCandidates()) {
out.write(candidate.toString());
out.newLine();
}
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void run(IAction action) {
IProviderDescription providerDefinition = view.getContentProviderDescription();
IGraphicalContentProvider contentProvider = view.getContentProvider();
if (providerDefinition == null)
providerDefinition = new PlaceholderProviderDescription(view.getInput(), contentProvider);
IFile selectedFile = view.getSelectedFile();
String suggestedName;
if (selectedFile == null)
suggestedName = "image";
else
suggestedName = selectedFile.getLocation().removeFileExtension().lastSegment();
boolean pathIsValid = false;
IPath path = null;
GraphicFileFormat fileFormat = null;
while (!pathIsValid) {
FileDialog saveDialog = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE);
saveDialog.setText("Choose a location to save to");
saveDialog.setFileName(suggestedName);
saveDialog.setFilterExtensions(contentProvider.getSupportedFormats().stream().map(it -> "*." + it.getExtension()).toArray(s -> new String[s]));
String pathString = saveDialog.open();
if (pathString == null)
return;
path = Path.fromOSString(pathString);
if (path.toFile().isDirectory()) {
MessageDialog.openError(null, "Invalid file path", "Location is already in use by a directory");
continue;
}
fileFormat = GraphicFileFormat.byExtension(path.getFileExtension());
if (fileFormat == null) {
MessageDialog.openError(null, "Invalid file extension", "Supported file formats are: "
+ contentProvider.getSupportedFormats().toString());
continue;
}
File parentDir = path.toFile().getParentFile();
parentDir.mkdirs();
if (parentDir.isDirectory())
pathIsValid = true;
else
MessageDialog.openError(null, "Invalid file path", "Could not create directory");
}
new SaveImageJob(fileFormat, path, providerDefinition).schedule();
}
/**
*
* @see org.eclipse.jface.action.Action#run()
*/
public void run() {
/*
* Open dialog for asking the user to enter some file names.
*/
FileDialog dialog = new FileDialog(this.window.getShell(), SWT.MULTI);
String[] individualFilters = Extensions
.getFiltersFromExtensions(Extensions.getBTFileExtensions());
String[] unifiedFilter = new String[] { Extensions
.getUnifiedFilterFromExtensions(Extensions
.getBTFileExtensions()) };
String[] filtersToUse = Extensions.joinArrays(individualFilters,
unifiedFilter);
dialog.setFilterExtensions(filtersToUse);
dialog.setText("Open BT");
/*
* If the user has selected at least one file name, we must open it.
* Note that the user may select several files.
*/
if (dialog.open() != null) {
/* Get the name of the files (NOT absolute path). */
String[] singleNames = dialog.getFileNames();
/*
* This vector will store the absolute path of every single selected
* file.
*/
Vector<String> absolutePath = new Vector<String>();
for (int i = 0, n = singleNames.length; i < n; i++) {
StringBuffer buffer = new StringBuffer(dialog.getFilterPath());
if (buffer.charAt(buffer.length() - 1) != File.separatorChar)
buffer.append(File.separatorChar);
buffer.append(singleNames[i]);
absolutePath.add(buffer.toString());
}
new OpenBTAction(absolutePath).run();
}
}
/**
* {@inheritDoc}
*/
@Override
protected String getNewInputObject() {
final FileDialog dialog = new FileDialog(getShell());
if (lastPath != null) {
if (new File(lastPath).exists()) {
dialog.setFilterPath(lastPath);
}
}
final String[] filterExtensions = new String[] {extention};
dialog.setFilterExtensions(filterExtensions);
final String filePath = dialog.open();
if (filePath != null) {
final File file = new File(filePath);
final String fileName = file.getName();
if (contains(fileName)) {
final MessageBox messageBox = new MessageBox(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.ICON_WARNING | SWT.OK | SWT.CANCEL);
messageBox.setText(ResourceString.getResourceString("dialog.title.warning"));
messageBox.setMessage(ResourceString.getResourceString("dialog.message.update.file"));
if (messageBox.open() == SWT.CANCEL) {
return null;
}
namePathMap.put(fileName, filePath);
return null;
}
namePathMap.put(fileName, filePath);
try {
lastPath = file.getParentFile().getCanonicalPath();
} catch (final IOException e) {}
return fileName;
}
return null;
}
protected String getSaveFilePath(final IEditorPart editorPart, final GraphicalViewer viewer, final ExportSetting exportSetting) {
final FileDialog fileDialog = new FileDialog(editorPart.getEditorSite().getShell(), SWT.SAVE);
fileDialog.setFilterPath(getBasePath());
final String[] filterExtensions = getFilterExtensions();
fileDialog.setFilterExtensions(filterExtensions);
final String fileName = getDiagramFileName(editorPart);
fileDialog.setFileName(fileName);
return fileDialog.open();
}