Java-記事本程式、檔案選擇對話方塊(JFileChooser)
阿新 • • 發佈:2019-01-04
基本的GUI基礎和IO基礎
核心程式碼
JFileChooser jfc = new JFileChooser();
jfc.setDialogTitle("另存為...");
// jfc.showOpenDialog(null); // 顯示開啟檔案對話方塊
jfc.showSaveDialog(null); // 顯示儲存檔案對話方塊
jfc.setVisible(true);
String filename = jfc.getSelectedFile().getAbsolutePath(); // 獲取選擇的檔案的絕對路徑
1 開啟檔案
2 儲存檔案
3 檔案選擇對話方塊
public class Base extends JFrame implements ActionListener{
private static final long serialVersionUID = -1131829311416485951L;
JTextArea jta = null;
JMenuBar jmb = null;
JMenu jm1 = null;
JMenuItem jmi1 = null, jmi2 = null;
public Base() {
jta = new JTextArea();
jmb = new JMenuBar();
jm1 = new JMenu("檔案");
jm1.setMnemonic('F');
jmi1 = new JMenuItem("開啟");
jmi2 = new JMenuItem("儲存");
jmi1.addActionListener(this);
jmi1.setActionCommand("open");
jmi2.addActionListener(this);
jmi2.setActionCommand("save");
this.setJMenuBar(jmb);
jmb.add(jm1);
jm1.add(jmi1);
jm1.addSeparator();
jm1.add(jmi2);
this .add(jta);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400, 300);
this.setVisible(true);
}
//------------------------------------------------------
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("open")) {
// 檔案選擇視窗
JFileChooser jfc1 = new JFileChooser();
jfc1.setDialogTitle("請選擇檔案...");
jfc1.showOpenDialog(null);
jfc1.setVisible(true);
// 得到使用者選擇的檔案路徑
String filename = jfc1.getSelectedFile().getAbsolutePath();
// System.out.println(filename);
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filename));
String s = "";
String allCon = "";
while((s=br.readLine())!=null) {
allCon+=s+"\r\n";
}
jta.setText(allCon);
} catch (Exception e1) {
e1.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
} else if(e.getActionCommand().equals("save")) {
JFileChooser jfc2 = new JFileChooser();
jfc2.setDialogTitle("另存為...");
jfc2.showSaveDialog(null);
jfc2.setVisible(true);
String filename = jfc2.getSelectedFile().getAbsolutePath();
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(filename));
bw.write(this.jta.getText());
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
bw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}