How to “Open” and “Save” using java

一曲冷凌霜 提交于 2019-11-26 15:51:50

问题


I want to make an "Open" and "Save" dialog in java. An example of what I want is in the images below:

Open:

Save:

How would I go about doing this?


回答1:


I would suggest looking into javax.swing.JFileChooser

Here is a site with some examples in using as both 'Open' and 'Save'. http://www.java2s.com/Code/Java/Swing-JFC/DemonstrationofFiledialogboxes.htm

This will be much less work than implementing for yourself.




回答2:


You want to use a JFileChooser object. It will open and be modal, and block in the thread that opened it until you choose a file.

Open:

JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) {
  File file = fileChooser.getSelectedFile();
  // load from file
}

Save:

JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) {
  File file = fileChooser.getSelectedFile();
  // save to file
}

There are more options you can set to set the file name extension filter, or the current directory. See the API for the javax.swing.JFileChooser for details. There is also a page for "How to Use File Choosers" on Oracle's site:

http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html




回答3:


Maybe you could take a look at JFileChooser, which allow you to use native dialogs in one line of code.




回答4:


You can find an introduction to file dialogs in the Java Tutorials. Java2s also has some example code.




回答5:


First off, you'll want to go through Oracle's tutorial to learn how to do basic I/O in Java.

After that, you will want to look at the tutorial on how to use a file chooser.




回答6:


You may also want to consider the possibility of using SWT (another Java GUI library). Pros and cons of each are listed at:

Java Desktop application: SWT vs. Swing



来源:https://stackoverflow.com/questions/3548140/how-to-open-and-save-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!