下面列出了javax.swing.JFileChooser#showSaveDialog ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void onUnCompressFile(Compressor ma) {
File file = getSelectedArchiverFile(ma.getFileFilter());
if (file == null) {
return;
}
String fn = file.getName();
fn = fn.substring(0, fn.lastIndexOf('.'));
JFileChooser s = new JFileChooser(".");
s.setSelectedFile(new File(fn));
s.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = s.showSaveDialog(this);
if (returnVal != JFileChooser.APPROVE_OPTION) {
return;
}
String filepath = s.getSelectedFile().getAbsolutePath();
try {
ma.doUnCompress(file, filepath);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void save(ActionEvent e, CycleView graph) {
int w = graph.getWidth();
int h = graph.getHeight();
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
graph.paint(img.createGraphics());
JFileChooser chooser = new JFileChooser(new File(System.getProperty("user.home")));
int c = chooser.showSaveDialog(graph);
if (c == JFileChooser.CANCEL_OPTION) {
System.out.println("cancel");
return;
}
try {
File f = chooser.getSelectedFile();
ImageIO.write(img, "png", f);
System.out.println(f.getAbsolutePath());
Desktop.getDesktop().open(f.getParentFile());
} catch (IOException e1) {
e1.printStackTrace();
}
}
private void loadFile() {
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("HTML Files (*.htm, *.html)", "htm", "html");
fileChooser.addChoosableFileFilter(filter);
fileChooser.addChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
fileChooser.setFileFilter(filter);
if (internalBalloon.getBalloonContentPath().isSetLastUsedMode()) {
fileChooser.setCurrentDirectory(new File(internalBalloon.getBalloonContentPath().getLastUsedPath()));
} else {
fileChooser.setCurrentDirectory(new File(internalBalloon.getBalloonContentPath().getStandardPath()));
}
int result = fileChooser.showSaveDialog(getTopLevelAncestor());
if (result == JFileChooser.CANCEL_OPTION) return;
try {
String exportString = fileChooser.getSelectedFile().toString();
browseText.setText(exportString);
internalBalloon.getBalloonContentPath().setLastUsedPath(fileChooser.getCurrentDirectory().getAbsolutePath());
internalBalloon.getBalloonContentPath().setPathMode(PathMode.LASTUSED);
}
catch (Exception e) {
//
}
}
private void loadFile() {
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("HTML Files (*.htm, *.html)", "htm", "html");
fileChooser.addChoosableFileFilter(filter);
fileChooser.addChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
fileChooser.setFileFilter(filter);
if (internalBalloon.getBalloonContentPath().isSetLastUsedMode()) {
fileChooser.setCurrentDirectory(new File(internalBalloon.getBalloonContentPath().getLastUsedPath()));
} else {
fileChooser.setCurrentDirectory(new File(internalBalloon.getBalloonContentPath().getStandardPath()));
}
int result = fileChooser.showSaveDialog(getTopLevelAncestor());
if (result == JFileChooser.CANCEL_OPTION) return;
try {
String exportString = fileChooser.getSelectedFile().toString();
browseText.setText(exportString);
internalBalloon.getBalloonContentPath().setLastUsedPath(fileChooser.getCurrentDirectory().getAbsolutePath());
internalBalloon.getBalloonContentPath().setPathMode(PathMode.LASTUSED);
}
catch (Exception e) {
//
}
}
/**
* 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 {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(this.defaultDirectoryForSaveAs);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
localizationResources.getString("PNG_Image_Files"), "png");
fileChooser.addChoosableFileFilter(filter);
fileChooser.setFileFilter(filter);
int option = fileChooser.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
String filename = fileChooser.getSelectedFile().getPath();
if (isEnforceFileExtensions()) {
if (!filename.endsWith(".png")) {
filename = filename + ".png";
}
}
ChartUtilities.saveChartAsPNG(new File(filename), this.chart,
getWidth(), getHeight());
}
}
private void saveKMLFile() {
JFileChooser aDlg = new JFileChooser();
String[] fileExts = new String[]{"kml"};
GenericFileFilter mapFileFilter = new GenericFileFilter(fileExts, "KML File (*.kml)");
aDlg.setFileFilter(mapFileFilter);
File dir = new File(System.getProperty("user.dir"));
if (dir.isDirectory()) {
aDlg.setCurrentDirectory(dir);
}
aDlg.setAcceptAllFileFilterUsed(false);
if (aDlg.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
File file = aDlg.getSelectedFile();
System.setProperty("user.dir", file.getParent());
String extent = ((GenericFileFilter) aDlg.getFileFilter()).getFileExtent();
String fileName = file.getAbsolutePath();
if (!fileName.substring(fileName.length() - extent.length()).equals(extent)) {
fileName = fileName + "." + extent;
}
_currentLayer.saveAsKMLFile(fileName);
this.setCursor(Cursor.getDefaultCursor());
}
}
/**
* 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 {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(this.defaultDirectoryForSaveAs);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
localizationResources.getString("PNG_Image_Files"), "png");
fileChooser.addChoosableFileFilter(filter);
fileChooser.setFileFilter(filter);
int option = fileChooser.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
String filename = fileChooser.getSelectedFile().getPath();
if (isEnforceFileExtensions()) {
if (!filename.endsWith(".png")) {
filename = filename + ".png";
}
}
ChartUtilities.saveChartAsPNG(new File(filename), this.chart,
getWidth(), getHeight());
}
}
/**
* 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 {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(this.defaultDirectoryForSaveAs);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
localizationResources.getString("PNG_Image_Files"), "png");
fileChooser.addChoosableFileFilter(filter);
fileChooser.setFileFilter(filter);
int option = fileChooser.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
String filename = fileChooser.getSelectedFile().getPath();
if (isEnforceFileExtensions()) {
if (!filename.endsWith(".png")) {
filename = filename + ".png";
}
}
ChartUtilities.saveChartAsPNG(new File(filename), this.chart,
getWidth(), getHeight());
}
}
public void openDocument() {
try {
File current = new File(".");
JFileChooser chooser = new JFileChooser(current);
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setFileFilter(new HTMLFileFilter());
int approval = chooser.showSaveDialog(this);
if (approval == JFileChooser.APPROVE_OPTION) {
currentFile = chooser.getSelectedFile();
setTitle(currentFile.getName());
FileReader fr = new FileReader(currentFile);
Document oldDoc = textPane.getDocument();
if (oldDoc != null)
oldDoc.removeUndoableEditListener(undoHandler);
HTMLEditorKit editorKit = new HTMLEditorKit();
document = (HTMLDocument) editorKit.createDefaultDocument();
editorKit.read(fr, document, 0);
document.addUndoableEditListener(undoHandler);
textPane.setDocument(document);
resetUndoManager();
}
} catch (BadLocationException ble) {
System.err.println("BadLocationException: " + ble.getMessage());
} catch (FileNotFoundException fnfe) {
System.err.println("FileNotFoundException: " + fnfe.getMessage());
} catch (IOException ioe) {
System.err.println("IOException: " + ioe.getMessage());
}
}
@Override
public void selectFolder(final Runnable callback) {
final boolean save = false;
JApplet applet = new JApplet(); // TODO fail safe
final JFileChooser fc = new JFileChooser(new File(path));
fc.setFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "Folder";
}
@Override
public boolean accept(File f) {
return f.isDirectory();
}
});
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int r = save ? fc.showSaveDialog(applet) : fc.showOpenDialog(applet);
if(r == JFileChooser.APPROVE_OPTION){
final File file = fc.getSelectedFile();
path = file.getPath();
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
lastFile = Gdx.files.absolute(file.getAbsolutePath());
callback.run();
}
});
}else{
// callback.cancel();
}
applet.destroy();
}
private void saveAsMenuActionPerformed(final java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveAsMenuActionPerformed
final JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
try {
final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(this.fileName), "UTF-8"));
writer.write(this.editPane.getText());
writer.close();
}
catch (IOException ioe) {
this.editPane.setText("Pardon. Can't write file. Please contact with: [email protected]mail.com");
}
}
}
/**
* Query the user for a filename and save the plot to that file.
*/
protected void _saveAs() {
JFileChooser fileDialog = new JFileChooser();
fileDialog.addChoosableFileFilter(new PLTOrXMLFileFilter());
fileDialog.setDialogTitle("Save plot as...");
if (_directory != null) {
fileDialog.setCurrentDirectory(_directory);
} else {
// The default on Windows is to open at user.home, which is
// typically an absurd directory inside the O/S installation.
// So we use the current directory instead.
String cwd = StringUtilities.getProperty("user.dir");
if (cwd != null) {
fileDialog.setCurrentDirectory(new File(cwd));
}
}
fileDialog.setSelectedFile(new File(fileDialog.getCurrentDirectory(), "plot.xml"));
int returnVal = fileDialog.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
_file = fileDialog.getSelectedFile();
setTitle(_file.getName());
_directory = fileDialog.getCurrentDirectory();
_save();
}
}
private void jButton_SaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_SaveActionPerformed
// TODO add your handling code here:
String path = System.getProperty("user.dir");
File pathDir = new File(path);
JFileChooser outDlg = new JFileChooser();
outDlg.setCurrentDirectory(pathDir);
String[] fileExts;
GenericFileFilter txtFileFilter;
if (this._data instanceof GridData) {
fileExts = new String[]{"dat"};
txtFileFilter = new GenericFileFilter(fileExts, "Surfer ASCII file (*.dat)");
} else {
fileExts = new String[]{"csv"};
txtFileFilter = new GenericFileFilter(fileExts, "CSV file (*.csv)");
}
outDlg.setFileFilter(txtFileFilter);
outDlg.setAcceptAllFileFilterUsed(false);
if (JFileChooser.APPROVE_OPTION == outDlg.showSaveDialog(this)) {
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
String fileName = outDlg.getSelectedFile().getAbsolutePath();
String extent = ((GenericFileFilter) outDlg.getFileFilter()).getFileExtent();
if (!fileName.substring(fileName.length() - extent.length()).equals(extent)) {
fileName = fileName + "." + extent;
}
if (this._data instanceof GridData) {
((GridData) this._data).saveAsSurferASCIIFile(fileName);
} else {
((StationData) this._data).saveAsCSVFile(fileName, this._colNames[this._colNames.length - 1]);
}
this.setCursor(Cursor.getDefaultCursor());
}
}
private SelectedFile selectExportTargetFile(final ExportProvider exportProvider) {
File targetDir;
String targetName;
String defaultName = exportProvider.getViewName();
// 1. let the user choose file or directory
final JFileChooser chooser = getFileChooser();
if (exportDir != null) {
chooser.setCurrentDirectory(exportDir);
}
int result = chooser.showSaveDialog(WindowManager.getDefault().getRegistry().getActivated());
if (result != JFileChooser.APPROVE_OPTION) {
return null; // cancelled by the user
}
// 2. process both cases and extract file name and extension to use and set exported file type
File file = chooser.getSelectedFile();
String targetExt = null;
FileFilter selectedFileFilter = chooser.getFileFilter();
if (selectedFileFilter==null // workaround for #227659
|| selectedFileFilter.getDescription().equals(Bundle.ExportAction_ExportDialogCSVFilter())) {
targetExt=FILE_EXTENSION_CSV;
exportedFileType=MODE_CSV;
} else if (selectedFileFilter.getDescription().equals(Bundle.ExportAction_ExportDialogTXTFilter())) {
targetExt=FILE_EXTENSION_TXT;
exportedFileType=MODE_TXT;
} else if (selectedFileFilter.getDescription().equals(Bundle.ExportAction_ExportDialogBINFilter())) {
targetExt=FILE_EXTENSION_BIN;
exportedFileType=MODE_BIN;
}
if (file.isDirectory()) { // save to selected directory under default name
exportDir = file;
targetDir = file;
targetName = defaultName;
} else { // save to selected file
targetDir = fileChooser.getCurrentDirectory();
String fName = file.getName();
// divide the file name into name and extension
if (fName.endsWith("."+targetExt)) { // NOI18N
int idx = fName.lastIndexOf('.'); // NOI18N
targetName = fName.substring(0, idx);
} else { // no extension
targetName=fName;
}
}
// 3. set type of exported file and return a newly created FileObject
return new ExportAction.SelectedFile(targetDir, targetName, targetExt);
}
/**
* Action called when Save List button is pressed.
*/
public void actionSaveList() {
try {
JFileChooser fc = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter(GT._T("XML files"), "xml");
fc.addChoosableFileFilter(filter);
fc.setFileFilter(filter);
Configuration config = Configuration.getConfiguration();
String directory = config.getString(getWiki(), ConfigurationValueString.LAST_REPLACEMENTS_DIRECTORY);
if (directory != null) {
fc.setCurrentDirectory(new File(directory));
}
int returnVal = fc.showSaveDialog(getParentComponent());
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
// Check if file exists
if (file.exists()) {
int answer = displayYesNoWarning(
GT._T("This file exists, do you want to overwrite it?"));
if (answer != JOptionPane.YES_OPTION) {
return;
}
}
// Save file
JAXBContext context = JAXBContext.newInstance(AutomaticFixingList.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
AutomaticFixingList list = new AutomaticFixingList();
list.setReplacements(modelAutomaticFixing.getData());
list.setComment(getComment());
list.setAdditionalAlgorithms(
CheckErrorAlgorithms.convertToIntegerList(automaticCWAlgorithms));
list.setForceAlgorithms(
CheckErrorAlgorithms.convertToIntegerList(forceCWAlgorithms));
m.marshal(list, file);
config.setString(
getWiki(), ConfigurationValueString.LAST_REPLACEMENTS_DIRECTORY,
file.getParentFile().getAbsolutePath());
}
} catch (JAXBException e) {
Utilities.displayError(getParentComponent(), e);
}
}
protected void createParalel() {
Function f = null;
try {
final JFileChooser chooser = new JFileChooser() {
@Override
public void approveSelection() {
if (getSelectedFile().exists()) {
if (JOptionPane
.showConfirmDialog(
framework.getMainFrame(),
GlobalResourcesManager
.getString("File.Exists"),
UIManager
.getString("OptionPane.messageDialogTitle"),
JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION)
return;
}
super.approveSelection();
}
};
if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
final CreateParalelDialog dialog = new CreateParalelDialog(
framework.getMainFrame());
if (!dialog.showModal())
return;
String fn = chooser.getSelectedFile().getAbsolutePath();
if (!fn.substring(fn.length() - frame.FILE_EX.length())
.equalsIgnoreCase(frame.FILE_EX))
fn += frame.FILE_EX;
f = ((MovingFunction) movingArea.getActiveObject())
.getFunction();
frame.propertyChange(MChangeListener.FILE_SAVE, null);
boolean clearFunctionalBlock = dialog.getCreateParalelModel()
.isClearFunctionalBlock();
dataPlugin.createParalel(f, dialog.getCreateParalelModel()
.isCopyAllRows(), clearFunctionalBlock, new File(fn),
framework, movingArea.getDataPlugin());
movingArea.repaint();
}
} catch (final IOException e) {
JOptionPane.showMessageDialog(framework.getMainFrame(),
e.getLocalizedMessage());
}
}
@Override
public void onClick(ActionEvent arg0)
{
if ( JavaHelp.isNull(this.getAppFrame().getTableName()) )
{
this.getAppFrame().showHintInfo("请先选择要导出的表" ,Color.BLUE);
return;
}
if ( this.getAppFrame().getRowCount() == 0 )
{
this.getAppFrame().showHintInfo("查询结果无数据,无法导出" ,Color.BLUE);
return;
}
JTable v_JTable = (JTable)XJava.getObject("xtDataList");
int [] v_RowIndexArr = v_JTable.getSelectedRows();
StringBuilder v_FileName = new StringBuilder();
// 生成文件名称
v_FileName.append(this.getTableName());
if ( v_RowIndexArr.length <= 0 )
{
String v_Text = "";
v_Text = ((JTextComponent)XJava.getObject("RowKey")) .getText();
if ( !JavaHelp.isNull(v_Text) )
{
v_FileName.append("_R.").append(v_Text.trim());
}
v_Text = ((JComboBox) XJava.getObject("FamilyName")) .getSelectedItem().toString();
if ( !JavaHelp.isNull(v_Text) )
{
v_FileName.append("_F.").append(v_Text.trim());
}
v_Text = ((JComboBox) XJava.getObject("ColumnName")) .getSelectedItem().toString();
if ( !JavaHelp.isNull(v_Text) )
{
v_FileName.append("_C.").append(v_Text.trim());
}
v_Text = ((JTextComponent)XJava.getObject("ColumnValue")).getText();
if ( !JavaHelp.isNull(v_Text) )
{
v_FileName.append("_V.").append(v_Text.trim());
}
}
else
{
v_FileName.append("_CCount.").append(v_RowIndexArr.length);
v_FileName.append("_").append(Date.getNowTime().getFull_ID());
}
v_FileName.append(".txt");
File v_SaveFile = new File(v_FileName.toString());
JFileChooser v_FileChooser = new JFileChooser();
v_FileChooser.setSelectedFile(v_SaveFile);
int v_Result = v_FileChooser.showSaveDialog(this.getAppFrame());
if ( v_Result == JFileChooser.APPROVE_OPTION )
{
v_SaveFile = v_FileChooser.getSelectedFile();
this.writeContents(v_JTable ,v_RowIndexArr ,v_SaveFile);
}
}
/**
* Install the game.
* @param askDir ask for the installation directory?
*/
void doInstall(boolean askDir) {
if (askDir) {
JFileChooser fc = new JFileChooser(installDir);
fc.setMultiSelectionEnabled(false);
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) {
return;
}
installDir = fc.getSelectedFile();
} else {
installDir = currentDir;
}
final LModule g = updates.getModule(GAME);
showHideProgress(true);
currentAction.setText(label("Checking existing game files..."));
currentFileProgress.setText("0%");
totalFileProgress.setText("0%");
fileProgress.setValue(0);
totalProgress.setValue(0);
install.setVisible(false);
update.setVisible(false);
verifyBtn.setVisible(false);
cancel.setVisible(true);
totalProgress.setVisible(true);
totalFileProgress.setVisible(true);
totalFileProgressLabel.setVisible(true);
worker = new SwingWorker<List<LFile>, Void>() {
@Override
protected List<LFile> doInBackground() throws Exception {
return collectDownloads(g);
}
@Override
protected void done() {
showHideProgress(false);
worker = null;
cancel.setVisible(false);
try {
doDownload(get());
} catch (CancellationException ex) {
} catch (ExecutionException | InterruptedException ex) {
Exceptions.add(ex);
errorMessage(format("Error while checking files: %s", ex));
}
}
};
worker.execute();
}
private void doSaveSettings() {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Save as...");
chooser.setMultiSelectionEnabled(false);
chooser.setCurrentDirectory(workingDirectory);
int returnVal = chooser.showSaveDialog(Utils.getActiveFrame());
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
saveSettings(file);
File tmpDir = chooser.getCurrentDirectory();
if (tmpDir != null) {
workingDirectory = tmpDir;
}
setStatus("Saved as " + file.getAbsolutePath());
}// END: approve check
}
/**
* This method creates and shows a file chooser, depending on the operating
* system. In case the os is Windows or Linux, the standard
* Swing-JFileChooser will be opened. In case the os is Mac OS X, the old
* awt-dialog is used, which looks more nativ.<br><br>
* When the user chose a file, it will be returned, else {@code null} will
* be returned.
*
* @param parent the parent-frame of the file chooser
* @param dlgmode<br>
* - in case of Mac OS X: either {@code FileDialog.LOAD} or
* {@code FileDialog.SAVE} - else: {@code JFileChooser.OPEN_DIALOG} or
* {@code JFileChooser.SAVE_DIALOG}
* @param filemode<br>
* - not important for Mac OS X. - else: {@code JFileChooser.FILES_ONLY} or
* the other file-selection-mode-values
* @param initdir the initial directory which can be set when the dialog is
* shown
* @param initfile the initial file which can be selected when the dialog is
* shown
* @param title the dialog's title
* @param acceptedext the accepted file extensions that will be accepted,
* i.e. the files that are selectable
* @param desc the description of which file types the extensions are
* @param settings a reference to the CSettings-class
* @return The chosen file, or {@code null} if dialog was cancelled
*/
public static File chooseFile(java.awt.Frame parent, int dlgmode, int filemode, String initdir, String initfile, String title, final String[] acceptedext, final String desc, Settings settings) {
File curdir = (null == initdir) ? null : new File(initdir);
JFileChooser fc = createFileChooser(title, filemode, curdir, acceptedext, desc);
int option = (JFileChooser.OPEN_DIALOG == dlgmode) ? fc.showOpenDialog(parent) : fc.showSaveDialog(parent);
if (JFileChooser.APPROVE_OPTION == option) {
return fc.getSelectedFile();
}
return null;
}