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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…