-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileOpenAndSaveTest.java
61 lines (57 loc) · 1.74 KB
/
FileOpenAndSaveTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package java_GUI;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
public class FileOpenAndSaveTest {
public static void main(String[] args) {
JFrame f = new JFrame("打开和保存文件");
f.setLayout(new FlowLayout());
JFileChooser fc = new JFileChooser();
fc.setFileFilter(new FileFilter() {
@Override
public String getDescription() {
return ".txt";
}
@Override
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".txt");
}
});
JButton bOpen = new JButton("打开文件");
JButton bSave = new JButton("保存文件");
f.add(bOpen);
f.add(bSave);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(250, 150);
f.setLocationRelativeTo(null);
f.setVisible(true);
//打开文件按钮点击监听器
bOpen.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int returnVal = fc.showOpenDialog(f);
File file = fc.getSelectedFile();
if (returnVal == JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(f, "计划打开文件:" + file.getAbsolutePath());
}
}
});
//保存文件按钮点击监听器
bSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int returnVal = fc.showSaveDialog(f);
File file = fc.getSelectedFile();
if (returnVal == JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(f, "计划保存到文件:" + file.getAbsolutePath());
}
}
});
}
}