import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class MenuDemo
{
private Frame f;
private MenuBar mb;
private Menu m;
private MenuItem dm,gm,bm;
private FileDialog open,save;
private TextArea ta;
private File file;
MenuDemo()
{
init();
}
public void init()
{
f=new Frame("魔兽世界");
mb=new MenuBar();
m=new Menu("文件");
dm=new MenuItem("打开");
gm=new MenuItem("退出");
bm=new MenuItem("保存");
open=new FileDialog(f,"打开WoW",FileDialog.LOAD);
save=new FileDialog(f,"关闭WoW",FileDialog.SAVE);
ta=new TextArea();
f.setBounds(300,100,600,600);
//f.setLayout(new FlowLayout());使用默认布局,没设置东南西北,就填充了
f.setMenuBar(mb);
f.add(ta);
mb.add(m);
m.add(dm);
m.add(bm);
m.add(gm);
myEvent();
f.setVisible(true);
}
private void myEvent()
{
bm.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(file==null)
{
save.setVisible(true);
String s1=save.getFile();
String s2=save.getDirectory();
if (s1==null||s2==null)
{
return;
}
file=new File(s2,s1);
}
try
{
BufferedWriter bw=new BufferedWriter(new FileWriter(file));
String s=ta.getText();
bw.write(s);
bw.flush();
bw.close();
}
catch (IOException e1)
{
throw new RuntimeException("写入失败");
}
}
});
dm.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
open.setVisible(true);
String filePath=open.getDirectory();
String name=open.getFile();
if (filePath==null||name==null)
{
return;
}
ta.setText("");
file=new File(filePath,name);
BufferedReader br=null;
try
{
br=new BufferedReader(new FileReader(file));
String line=null;
while ((line=br.readLine())!=null)
{
ta.append(line+"\r\n");
}
}
catch (IOException e1)
{
throw new RuntimeException("读取失败");
}
finally
{
try
{
if (br!=null)
{
br.close();
}
}
catch (IOException e1)
{
System.out.println("读取流关闭失败");
}
}
}
});
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
gm.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public static void main(String[] args)
{
new MenuDemo();
}
}
简易记事本,只有保存,打开,退出3个功能!
最新推荐文章于 2022-01-16 19:02:04 发布