@Override public void actionPerformed(ActionEvent e) { if (td.getTabCount() > 0) { JFileChooser f = new JFileChooser(); f.setFileFilter(new MyFileFilter()); int choose = f.showSaveDialog(getContentPane()); if (choose == JFileChooser.APPROVE_OPTION) { BufferedWriter brw = null; try { File file = f.getSelectedFile(); brw = new BufferedWriter(new FileWriter(file)); int i = td.getSelectedIndex(); TextDocument ta = (TextDocument) td.getComponentAt(i); ta.write(brw); ta.fileName = file.getName(); // 將檔案名稱更新為存檔的名稱 td.setTitleAt(td.getSelectedIndex(), ta.fileName); ta.file = file; ta.save = true; // 設定已儲存 System.out.println("Save as pass!"); td.setTitleAt(i, ta.fileName); // 更新標題名稱 } catch (Exception exc) { exc.printStackTrace(); } finally { try { brw.close(); } catch (Exception ecx) { ecx.printStackTrace(); } } } } else { JOptionPane.showMessageDialog(null, "沒有檔案可以儲存!"); } }
@Override public void actionPerformed(ActionEvent e) { JFileChooser f = new JFileChooser(); f.setFileFilter(new MyFileFilter()); // 設定檔案選擇器 int choose = f.showOpenDialog(getContentPane()); // 顯示檔案選取 if (choose == JFileChooser.OPEN_DIALOG) { // 有開啟檔案的話,開始讀檔 BufferedReader br = null; try { File file = f.getSelectedFile(); br = new BufferedReader(new FileReader(file)); TextDocument ta = new TextDocument(file.getName(), file); ta.addKeyListener(new SystemTrackSave()); ta.read(br, null); td.add(ta); td.setTitleAt(docCount++, file.getName()); } catch (Exception exc) { exc.printStackTrace(); } finally { try { br.close(); } catch (Exception ecx) { ecx.printStackTrace(); } } } }