package com.practice4;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class MyNotepad extends Frame implements ActionListener{
MenuBar mb;
Menu m1,m2;
MenuItem mi_open,mi_save,mi_saveAs,mi_exit;
TextArea ta;
String sfd="";
FileDialog fd_file,fd_save,fd_saveAs;
BufferedReader br=null;
BufferedWriter bw=null;
public MyNotepad()
{
super("記事本");
m1=new Menu("檔案");
m2=new Menu("協助");
mb=new MenuBar();
ta=new TextArea();
mi_open=new MenuItem("開啟");
mi_save=new MenuItem("儲存");
mi_saveAs=new MenuItem("另存新檔");
mi_exit=new MenuItem("退出");
fd_file=new FileDialog(this,"開啟",FileDialog.LOAD);
fd_save=new FileDialog(this,"儲存",FileDialog.SAVE);
mb.add(m1);
mb.add(m2);
m1.add(mi_open);
m1.add(mi_save);
m1.add(mi_saveAs);
m1.add(mi_exit);
mi_open.addActionListener(this);
mi_save.addActionListener(this);
mi_saveAs.addActionListener(this);
mi_exit.addActionListener(this);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.setMenuBar(mb);
add(ta);
setBounds(200,200,750,650);
setVisible(true);
}
public static void main(String[] args) {
new MyNotepad();
}
public void actionPerformed(ActionEvent e) {
String s=e.getActionCommand();
if(s.equals("開啟"))
{
fd_file.setVisible(true);
String stf=fd_file.getFile();
String std=fd_file.getDirectory();
if((stf!=null)&&(std!=null))
{
sfd=stf+std;
openFile(sfd);
}
}else if(s.equals("儲存"))
{
if(sfd==null||sfd.equals(""))
{
saveFileAs(sfd);
}
else
saveFile(sfd);
}else if(s.equals("另存新檔"))
{
saveFileAs(sfd);
}else if(s.equals("退出"))
{
System.exit(0);
}
}
public void openFile(String s)
{
ta.setText("");
setTitle(sfd+"-記事本");
try{
br=new BufferedReader(new FileReader(s));
String st=br.readLine();
while(st!=null)
{
ta.append(st+"\n");
st=br.readLine();
}
}catch(IOException e)
{
e.toString();
}finally{
if(br!=null)
try{
br.close();
}catch(IOException e)
{
e.toString();
}
}
}
public void saveFile(String s)
{
String st=ta.getText();
try{
PrintWriter pw=new PrintWriter(new FileWriter(s));
pw.println(st);
}catch(IOException e)
{
e.toString();
}finally
{
if(bw!=null)
try{
bw.close();
}catch(IOException e)
{
e.toString();
}
}
}
public void saveFileAs(String s)
{
fd_save.setVisible(true);
String std=fd_save.getDirectory();
String stf=fd_save.getFile();
if((std!=null)&&(stf!=null))
{
sfd=std+stf;
saveFile(sfd);
setTitle(sfd+"-記事本");
}
}
}