我是Swing的新手,希望在我的Swing代码中实现下载文件功能,允许用户保存或打开特定文件.
我确实看过JFileChooser.showOpenDialog和showSaveDialog,但我不想使用它,因为它让我可以选择从文件系统中选择任何文件.
希望我的问题很清楚.请帮我解决一下这个.
您想要使用它们,并添加一个过滤器.例如:
JFileChooser chooser = new JFileChooser();
// Note: source for ExampleFileFilter can be found in FileChooserDemo,
// under the demo/jfc directory in the Java 2 SDK, Standard Edition.
ExampleFileFilter filter = new ExampleFileFilter();
filter.addExtension("jpg");
filter.setDescription("JPG & GIF Images");
chooser.setFileFilter(filter);
int returnVal = chooser.showSaveDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}
Run Code Online (Sandbox Code Playgroud)
这只会显示JPG和GIF文件.从这里偷来的例子
编辑:这样您就知道ExampleFileFilter实现了抽象类FileFilter
编辑:由于您知道文件的名称,您可以只使用一个打开的按钮并使用Runtime .getRuntime.exec('要打开的文件.doc'),并且应该在相应的应用程序中打开它.
为了保存,您仍然希望提示他们找出他们想要保存的位置,这样您仍然需要JFileChooser.我仍然会使用过滤器,并在必要时确定动态文件扩展名,然后执行:
JFileChooser chooser = new JFileChooser();
// Note: source for ExampleFileFilter can be found in FileChooserDemo,
// under the demo/jfc directory in the Java 2 SDK, Standard Edition.
String selectedFile = "The suggested save name.";
chooser.setSelectedFile(selectedFile);
ExampleFileFilter filter = new ExampleFileFilter();
String extension = "Do something to find your extension";
filter.addExtension(extension);
filter.setDescription("JPG & GIF Images");
chooser.setFileFilter(filter);
int returnVal = chooser.showSaveDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
//then write your code to write to disk
}
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.
| 归档时间: |
|
| 查看次数: |
6279 次 |
| 最近记录: |