import java.awt.*;
import java.awt.event.*;
import java.io.*;
class MMDemo
{private Frame f;
private MenuBar mb;
private Menu m;
private MenuItem mi,openItem,saveItem;
private FileDialog load,save;
private TextArea ta;
private File file;
MMDemo(){
init();
}
public void init(){
f=new Frame("my window");
f.setBounds(300,100,600,500);
mb=new MenuBar();
m=new Menu("文件");
mi=new MenuItem("退出");
openItem=new MenuItem("打开");
saveItem=new MenuItem("保存");
f.setMenuBar(mb);
mb.add(m);
m.add(openItem);
m.add(saveItem);
m.add(mi);
load=new FileDialog(f,"我要打开",FileDialog.LOAD);
save=new FileDialog(f,"我要保存",FileDialog.SAVE);
ta=new TextArea();
f.add(ta);
MyEvent();
f.setVisible(true);
}
public void MyEvent(){
saveItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(file==null)
{
save.setVisible(true);
String dirPath=load.getDirectory();
String fileNames=load.getFile();
if(dirPath==null || fileNames==null);
return;
file=new File(dirPath,fileNames);
}
try
{BufferedWriter bufw=new BufferedWriter(new FileWriter(file));
String text=ta.getText();
bufw.write(text);
//bufw.flush();
bufw.close();
}
catch (IOException ex)
{
throw new RuntimeException("写入失败");
}
}
});
openItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
load.setVisible(true);
String dirPath=load.getDirectory();
String fileNames=load.getFile();
if(dirPath==null ||fileNames==null)
return;
ta.setText("");
file=new File(dirPath,fileNames);
try
{
BufferedReader bufr=new BufferedReader(new FileReader(file));
String line=null;
while((line=bufr.readLine())!=null)
{
ta.append(line+"\r\n");
}
bufr.close();
}
catch (IOException ex)
{
throw new RuntimeException("读取失败");
}
}
});
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
mi.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
}
public static void main(String[] args)
{
new MMDemo();
}
}
52 无法访问的语句file=new File(dirPath,fileNames); |
|