下面列出了怎么用javax.swing.JFileChooser的API类实例代码及写法,或者点击链接到github查看源代码。
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setMultiSelectionEnabled(false);
String currentPath = txtFilename.getText();
if (currentPath.length() > 0) {
File currentFile = new File(currentPath);
File currentDir = currentFile.getParentFile();
if (currentDir != null && currentDir.exists())
fileChooser.setCurrentDirectory(currentDir);
}
int returnVal = fileChooser.showDialog(MZmineCore.getDesktop().getMainWindow(), "Select file");
if (returnVal == JFileChooser.APPROVE_OPTION) {
String selectedPath = fileChooser.getSelectedFile().getAbsolutePath();
txtFilename.setText(selectedPath);
}
}
/**
* Creates a replay file preview accessory for a JFileChooser.
* @param fileChooser file chooser to create the accessory for
* @return a replay file preview accessory for JFileChoosers
*/
public static JComponent createReplayFilePreviewAccessory( final JFileChooser fileChooser ) {
final ReplayInfoBox replayInfoBox = new ReplayInfoBox();
fileChooser.addPropertyChangeListener( new PropertyChangeListener() {
@Override
public void propertyChange( final PropertyChangeEvent event ) {
if ( JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals( event.getPropertyName() ) ) {
final File file = (File) event.getNewValue();
if ( file == null || file.isDirectory() )
return;
replayInfoBox.setReplayFile( file );
}
}
} );
return replayInfoBox;
}
/**
* 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());
}
}
@Override
public void actionPerformed(ActionEvent e) {
final FolderChooser folderChooser = new FolderChooser();
final Preferences preferences = SnapApp.getDefault().getPreferences();
String lastDir = preferences.get(PROPERTY_KEY_LAST_OPEN_TS_DIR, SystemUtils.getUserHomeDir().getPath());
folderChooser.setCurrentDirectory(new File(lastDir));
final int result = folderChooser.showOpenDialog(ProductLocationsPane.this);
if (result != JFileChooser.APPROVE_OPTION) {
return;
}
File currentDir = folderChooser.getSelectedFolder();
model.addDirectory(currentDir, recursive);
if (currentDir != null) {
preferences.put(PROPERTY_KEY_LAST_OPEN_TS_DIR, currentDir.getAbsolutePath());
}
}
private void menuNewProjectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuNewProjectActionPerformed
final JFileChooser folderChooser = new JFileChooser();
folderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
folderChooser.setDialogTitle("Create project folder");
folderChooser.setDialogType(JFileChooser.SAVE_DIALOG);
folderChooser.setApproveButtonText("Create");
folderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (folderChooser.showSaveDialog(Main.getApplicationFrame()) == JFileChooser.APPROVE_OPTION) {
final File file = folderChooser.getSelectedFile();
if (file.isDirectory()) {
if (file.list().length > 0) {
DialogProviderManager.getInstance().getDialogProvider().msgError(this, "File '" + file.getName() + "' already exists and non-empty!");
} else {
prepareAndOpenProjectFolder(file);
}
} else if (file.mkdirs()) {
prepareAndOpenProjectFolder(file);
} else {
LOGGER.error("Can't create folder : " + file); //NOI18N
DialogProviderManager.getInstance().getDialogProvider().msgError(this, "Can't create folder: " + file);
}
}
}
public VersionInfoFormImpl(Bindings bindings, JFileChooser fc) {
_languageCombo.setModel(new DefaultComboBoxModel(LanguageID.sortedValues()));
bindings.addOptComponent("versionInfo", VersionInfo.class, _versionInfoCheck)
.add("versionInfo.fileVersion", _fileVersionField)
.add("versionInfo.productVersion", _productVersionField)
.add("versionInfo.fileDescription", _fileDescriptionField)
.add("versionInfo.internalName", _internalNameField)
.add("versionInfo.originalFilename", _originalFilenameField)
.add("versionInfo.productName", _productNameField)
.add("versionInfo.txtFileVersion", _txtFileVersionField)
.add("versionInfo.txtProductVersion", _txtProductVersionField)
.add("versionInfo.companyName", _companyNameField)
.add("versionInfo.copyright", _copyrightField)
.add("versionInfo.trademarks", _trademarksField)
.add("versionInfo.languageIndex", _languageCombo, VersionInfo.DEFAULT_LANGUAGE_INDEX)
;
}
private Component createLocationSector() {
JPanel panel = new JPanel(new BorderLayout());
location = new JTextField();
location.setPreferredSize(new Dimension(180, location
.getPreferredSize().height));
JButton button = new JButton("...");
button.setToolTipText("Base.Location.ToolTip");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser(location.getText());
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(Preferences.this) == JFileChooser.APPROVE_OPTION) {
location.setText(chooser.getSelectedFile()
.getAbsolutePath());
}
}
});
panel.add(location, BorderLayout.CENTER);
panel.add(button, BorderLayout.EAST);
return panel;
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
int returnVal = fileChooser.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
Path proxyFile = fileChooser.getSelectedFile().toPath();
LambdaAttack.getLogger().log(Level.INFO, "Opening: {0}.", proxyFile.getFileName());
botManager.getThreadPool().submit(() -> {
try {
List<Proxy> proxies = Files.lines(proxyFile).distinct().map((line) -> {
String host = line.split(":")[0];
int port = Integer.parseInt(line.split(":")[1]);
InetSocketAddress address = new InetSocketAddress(host, port);
return new Proxy(Type.SOCKS, address);
}).collect(Collectors.toList());
LambdaAttack.getLogger().log(Level.INFO, "Loaded {0} proxies", proxies.size());
botManager.setProxies(proxies);
} catch (Exception ex) {
LambdaAttack.getLogger().log(Level.SEVERE, null, ex);
}
});
}
}
public ClassPathFormImpl(Bindings bindings, JFileChooser fc) {
bindings.addOptComponent("classPath", ClassPath.class, _classpathCheck)
.add("classPath.mainClass", _mainclassField)
.add("classPath.paths", _classpathList);
_fileChooser = fc;
ClasspathCheckListener cpl = new ClasspathCheckListener();
_classpathCheck.addChangeListener(cpl);
cpl.stateChanged(null);
_classpathList.setModel(new DefaultListModel());
_classpathList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
_classpathList.addListSelectionListener(new ClasspathSelectionListener());
_newClasspathButton.addActionListener(new NewClasspathListener());
_acceptClasspathButton.addActionListener(
new AcceptClasspathListener(_classpathField));
_removeClasspathButton.addActionListener(new RemoveClasspathListener());
_importClasspathButton.addActionListener(new ImportClasspathListener());
_classpathUpButton.addActionListener(new MoveUpListener());
_classpathDownButton.addActionListener(new MoveDownListener());
}
private File openFile() {
String home = System.getProperty("user.home"); // NOI18N
JFileChooser chooser = new JFileChooser(home);
chooser.setMultiSelectionEnabled(false);
chooser.setFileHidingEnabled(false);
int dlgResult = chooser.showOpenDialog(this);
if (JFileChooser.APPROVE_OPTION == dlgResult) {
File result = chooser.getSelectedFile();
if (result != null && !result.exists()) {
result = null;
}
return result;
} else {
return null;
}
}
/**
* Selects a file to use as target for the operation.
*
* @param selectedFile
* the selected file.
* @param dialogType
* the dialog type.
* @param appendExtension
* true, if the file extension should be added if necessary, false if the unmodified filename should be used.
* @return the selected and approved file or null, if the user canceled the operation
*/
protected File performSelectFile( final File selectedFile, final int dialogType, final boolean appendExtension ) {
if ( this.fileChooser == null ) {
this.fileChooser = createFileChooser();
}
this.fileChooser.setSelectedFile( selectedFile );
this.fileChooser.setDialogType( dialogType );
final int option = this.fileChooser.showDialog( this.parent, null );
if ( option == JFileChooser.APPROVE_OPTION ) {
final File selFile = this.fileChooser.getSelectedFile();
String selFileName = selFile.getAbsolutePath();
if ( StringUtils.endsWithIgnoreCase( selFileName, getFileExtension() ) == false ) {
selFileName = selFileName + getFileExtension();
}
return new File( selFileName );
}
return null;
}
private void exportUnitCharts() {
final JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
final File rootDir = new File(SystemProperties.getUserDir());
final String defaultFileName =
FileNameUtils.removeIllegalCharacters(gameData.getGameName()) + "_unit_stats.html";
chooser.setSelectedFile(new File(rootDir, defaultFileName));
if (chooser.showSaveDialog(frame) != JOptionPane.OK_OPTION) {
return;
}
try (Writer writer =
Files.newBufferedWriter(chooser.getSelectedFile().toPath(), StandardCharsets.UTF_8)) {
writer.write(
HelpMenu.getUnitStatsTable(gameData, uiContext)
.replaceAll("</?p>|</tr>", "$0\r\n")
.replaceAll("(?i)<img[^>]+/>", ""));
} catch (final IOException e1) {
log.log(
Level.SEVERE,
"Failed to write unit stats: " + chooser.getSelectedFile().getAbsolutePath(),
e1);
}
}
/**
* Action performed.
*
* @param event the event
* @see java.awt.event.ActionListener#actionPerformed(ActionEvent)
*/
@Override
public void actionPerformed(ActionEvent event) {
try {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Load AE specifier file");
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
if (this.main.getAnnotOpenDir() != null) {
fileChooser.setCurrentDirectory(this.main.getAnnotOpenDir());
}
int rc = fileChooser.showOpenDialog(this.main);
if (rc == JFileChooser.APPROVE_OPTION) {
this.main.loadAEDescriptor(fileChooser.getSelectedFile());
}
this.main.setAllAnnotationViewerItemEnable(false);
} finally {
this.main.resetCursor();
}
}
/**
* Loads fit functions from an XML file chosen by the user.
*
* @return the path to the file opened, or null if none
*/
private String loadFits() {
if (chooser==null) {
chooser = OSPRuntime.getChooser();
for (FileFilter filter: chooser.getChoosableFileFilters()) {
if (filter.getDescription().toLowerCase().indexOf("xml")>-1) { //$NON-NLS-1$
chooser.setFileFilter(filter);
break;
}
}
}
int result = chooser.showOpenDialog(FitBuilder.this);
if(result==JFileChooser.APPROVE_OPTION) {
OSPRuntime.chooserDir = chooser.getCurrentDirectory().toString();
String fileName = chooser.getSelectedFile().getAbsolutePath();
return loadFits(fileName, false);
}
return null;
}
private void saveScriptToFile() {
File scriptFile = null;
try {
fc.setDialogTitle("Save R script");
fc.setDialogType(JFileChooser.SAVE_DIALOG);
int answer = fc.showDialog(Wandora.getWandora(), "Save");
if(answer == SimpleFileChooser.APPROVE_OPTION) {
scriptFile = fc.getSelectedFile();
String scriptCode = rEditor.getText();
FileUtils.writeStringToFile(scriptFile, scriptCode, null);
currentScriptSource = FILE_SOURCE;
}
}
catch(Exception e) {
WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "Exception '"+e.getMessage()+"' occurred while storing R script to file '"+scriptFile.getName()+"'.", "Can't save R script", WandoraOptionPane.INFORMATION_MESSAGE);
}
}
/**
* Ouvre la boîte de dialogue de choix de fichier image.
* <br>Retourne le fichier choisi, ou null si annulé.
* @param parent Component
* @param openOrSave boolean
* @param fileName String
* @return File
*/
public static File chooseImage(Component parent, boolean openOrSave, String fileName) {
final int result;
if (fileName != null) {
IMAGE_FILE_CHOOSER.setSelectedFile(new File(fileName));
}
if (openOrSave) {
result = IMAGE_FILE_CHOOSER.showOpenDialog(parent);
} else {
result = IMAGE_FILE_CHOOSER.showSaveDialog(parent);
}
if (result == JFileChooser.APPROVE_OPTION) {
File file = IMAGE_FILE_CHOOSER.getSelectedFile();
file = IMAGE_FILE_CHOOSER.checkFile(file);
return file;
}
return null;
}
private String getDirectory(String type, int filter) {
BaseDirectoryChooser gnuPlotDir = new BaseDirectoryChooser();
gnuPlotDir.setFileSelectionMode(filter);
int selection = -1;
if (type.equals("open"))
selection = gnuPlotDir.showOpenDialog(this);
if (selection == JFileChooser.APPROVE_OPTION) {
try {
return gnuPlotDir.getSelectedFile().getAbsolutePath();
} catch (Exception exp) {
}
}
return "";
}
/**
* Let the user choose a certificate file to export to.
*
* @param basename default filename (without extension)
* @return The chosen file or null if none was chosen
*/
private File chooseExportCertFile(String basename)
{
JFileChooser chooser = FileChooserFactory.getX509FileChooser(basename);
File fLastDir = m_lastDir.getLastDir();
if (fLastDir != null)
{
chooser.setCurrentDirectory(fLastDir);
}
chooser.setDialogTitle(RB.getString("FPortecle.ExportCertificate.Title"));
chooser.setMultiSelectionEnabled(false);
int iRtnValue = chooser.showDialog(this, RB.getString("FPortecle.Export.button"));
if (iRtnValue == JFileChooser.APPROVE_OPTION)
{
return chooser.getSelectedFile();
}
return null;
}
/**
* Sets the selected.
*
* @param s the new selected
*/
public void setSelected(String s) {
field.setText(s);
previousValue = s;
if (s == null || s.length() == 0) {
s = System.getProperty("user.dir");
}
File file = new File(s);
//only modify file chooser if it has already been created
if (this.fileChooser != null) {
if (this.fileChooser.getFileSelectionMode() == JFileChooser.FILES_ONLY && file.isDirectory()) {
this.fileChooser.setCurrentDirectory(file);
} else {
this.fileChooser.setSelectedFile(file);
}
}
}
void createFileChooser() {
formats = new Hashtable<String, ExportFormat>();
registerFormat(new ExportGnuplotFormat());
registerFormat(new ExportXMLFormat());
// Set the "filesOfTypeLabelText" to "File Format:"
Object oldFilesOfTypeLabelText = UIManager.put("FileChooser.filesOfTypeLabelText", //$NON-NLS-1$
ToolsRes.getString("ExportTool.FileChooser.Label.FileFormat")); //$NON-NLS-1$
// Create a new FileChooser
fc = new JFileChooser(OSPRuntime.chooserDir);
// Reset the "filesOfTypeLabelText" to previous value
UIManager.put("FileChooser.filesOfTypeLabelText", oldFilesOfTypeLabelText); //$NON-NLS-1$
fc.setDialogType(JFileChooser.SAVE_DIALOG);
fc.setDialogTitle(ToolsRes.getString("ExportTool.FileChooser.Title")); //$NON-NLS-1$
fc.setApproveButtonText(ToolsRes.getString("ExportTool.FileChooser.Button.Export")); // Set export formats //$NON-NLS-1$
setChooserFormats();
}
public void testSetSelectionApprover() throws Exception {
FileChooserBuilder instance = new FileChooserBuilder("i");
File tmp = getWorkDir();
assertTrue ("Environment is insane", tmp.exists() && tmp.isDirectory());
File sel = new File(tmp, "tmp" + System.currentTimeMillis());
if (!sel.exists()) {
assertTrue (sel.createNewFile());
}
instance.setDefaultWorkingDirectory(tmp);
SA sa = new SA();
instance.setSelectionApprover(sa);
JFileChooser ch = instance.createFileChooser();
ch.setSelectedFile(sel);
ch.approveSelection();
sa.assertApproveInvoked(sel);
}
private static void showExportDialog(final JFileChooser fileChooser, final Component parent, final ExportProvider[] providers) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (fileChooser.showDialog(parent, BUTTON_EXPORT) != JFileChooser.APPROVE_OPTION) return;
File targetFile = fileChooser.getSelectedFile();
FileFilter filter = fileChooser.getFileFilter();
for (ExportProvider provider : providers) {
FormatFilter format = provider.getFormatFilter();
if (filter.equals(format)) {
targetFile = checkFileExtension(targetFile, format.getExtension());
if (checkFileExists(targetFile)) provider.export(targetFile);
else showExportDialog(fileChooser, parent, providers);
break;
}
}
}
});
}
private static void createAndShowGUI() {
file = getTempFile();
final JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 300);
fileChooser = new JFileChooser(file.getParentFile());
fileChooser.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
defaultKeyPressed = true;
frame.dispose();
}
});
frame.getContentPane().add(BorderLayout.CENTER, fileChooser);
frame.setSize(fileChooser.getPreferredSize());
frame.setVisible(true);
}
void exportPlacemarkDataTable() {
final SnapFileChooser fileChooser = new SnapFileChooser();
fileChooser.setDialogTitle(MessageFormat.format("Export {0} Data Table", /*I18N*/
StringUtils.firstLetterUp(placemarkDescriptor.getRoleLabel())));
setComponentName(fileChooser, "Export_Data_Table");
fileChooser.setFileFilter(PlacemarkIO.createTextFileFilter());
final File ioDir = getIODir();
fileChooser.setCurrentDirectory(ioDir);
fileChooser.setSelectedFile(new File(ioDir, "Data"));
int result = fileChooser.showSaveDialog(SwingUtilities.getWindowAncestor(this));
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (file != null) {
if (Boolean.TRUE.equals(Dialogs.requestOverwriteDecision(getTitle(), file))) {
setIODir(file.getAbsoluteFile().getParentFile());
file = FileUtils.ensureExtension(file, PlacemarkIO.FILE_EXTENSION_FLAT_TEXT);
try {
try (Writer writer = new FileWriter(file)) {
writePlacemarkDataTableText(writer);
}
} catch (IOException ignored) {
Dialogs.showError(MessageFormat.format("I/O Error.\nFailed to export {0} data table.", /*I18N*/
placemarkDescriptor.getRoleLabel()));
}
}
}
}
}
protected void selectFile() {
ResourceManager rm = ResourceManager.all(FilePropertyEditor.class);
JFileChooser chooser = UserPreferences.getDefaultDirectoryChooser();
chooser.setDialogTitle(rm.getString("DirectoryPropertyEditor.dialogTitle"));
chooser.setApproveButtonText(
rm.getString("DirectoryPropertyEditor.approveButtonText"));
chooser.setApproveButtonMnemonic(
rm.getChar("DirectoryPropertyEditor.approveButtonMnemonic"));
File oldFile = (File)getValue();
if (oldFile != null && oldFile.isDirectory()) {
try {
chooser.setCurrentDirectory(oldFile.getCanonicalFile());
} catch (IOException e) {
e.printStackTrace();
}
}
if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(editor)) {
File newFile = chooser.getSelectedFile();
String text = newFile.getAbsolutePath();
textfield.setText(text);
firePropertyChange(oldFile, newFile);
}
}
private static void checkFileChooser() throws Exception {
if (System.getSecurityManager() == null) {
throw new RuntimeException("Security manager is not set!");
}
Robot robot = new Robot();
robot.setAutoDelay(50);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
fileChooser = new JFileChooser();
fileChooser.showOpenDialog(null);
fileChooserIsShown = true;
System.out.println("Start file chooser: " + fileChooserIsShown);
}
});
long time = System.currentTimeMillis();
while (fileChooser == null) {
if (System.currentTimeMillis() - time >= 10000) {
throw new RuntimeException("FileChoser is not shown!");
}
Thread.sleep(500);
}
Thread.sleep(500);
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
System.exit(0);
}
/**
* Returns the file chooser.
*
* @return the file chooser
*/
public synchronized JFileChooser get() {
while (fileChooser == null) {
try {
wait();
} catch (InterruptedException e) {
}
}
return fileChooser;
}
/**
* @param seletMode
* @return
*/
public String showDialog(int seletMode)
{
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(seletMode);
chooser.setMultiSelectionEnabled(true);//璁剧疆澶氶?鏂囦欢
int result = chooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION)
{
String filePath = chooser.getSelectedFile().getAbsolutePath();
return filePath;
}
return null;
}
private int err() {
try {
throw new java.lang.IllegalAccessException("Warning! AsyncFileChooser interface bypassed!");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return JFileChooser.ERROR_OPTION;
}
private String getFileToOpen() {
JFileChooser projectFC = new JFileChooser(browserPath);
int validPath = projectFC.showOpenDialog(myCP);
if (validPath == JFileChooser.ERROR_OPTION || validPath == JFileChooser.CANCEL_OPTION) {
return null;
} else {
return projectFC.getSelectedFile().toString();
}
}