import java.io.*;
import java.awt.*;
import java.awt.event.*;
class MyMenuTest
{
private Frame f;
private MenuBar bar;
private Menu fileMenu;
private MenuItem openItem,saveItem,closeItem;
private TextArea ta;
private FileDialog openDia,saveDia;
private File file;
MyMenuTest()
{
init();
}
public void init()
{ f = new Frame ("夏尔的记事本");
f.setBounds(300,100,600,500);
bar = new MenuBar();
fileMenu = new Menu("文件");
openItem =new MenuItem("打开");
saveItem = new MenuItem("保存");
closeItem = new MenuItem("退出");
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(closeItem);
bar.add(fileMenu);
f.setMenuBar(bar);
openDia = new FileDialog(f,"我被夏尔打开了",FileDialog.LOAD);
saveDia = new FileDialog(f,"我要保存",FileDialog.SAVE);
ta = new TextArea();
f.add(ta);
myEvent();
f.setVisible(true);
}
private void myEvent()
{
saveItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{ if(file==null)
saveDia.setVisible(true);
String dirPath = saveDia.getDirectory();
String fileName = saveDia.getFile();
if(dirPath==null||fileName==null)
return;
file = new File(dirPath,fileName);
BufferedWriter bufw = null;
try
{
bufw = new BufferedWriter(new FileWriter(file));
String text = ta.getText();
bufw.write(text);
bufw.flush();
}
catch (IOException ex)
{
throw new RuntimeException("shibai");
}
finally
{
try
{
if(bufw!=null)
bufw.close();
}
catch (IOException ex)
{
throw new RuntimeException("");
}
}
}
});
openItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openDia.setVisible(true);
String dirPath = openDia.getDirectory();
String fileName =openDia.getFile();
if(dirPath==null||fileName==null)
return;
file = new File(dirPath,fileName);
ta.setText("");
BufferedReader bufr =null;
try
{ bufr = new BufferedReader(new FileReader(file));
String line = null;
while((line=bufr.readLine())!=null)
ta.append(line+"\r\n");
}
catch (IOException ex)
{
throw new RuntimeException("");
}
finally
{
try
{if(bufr!=null)
bufr.close();
}
catch (IOException ex)
{
throw new RuntimeException("");
}
}
}
});
closeItem.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
f.addWindowListener(new WindowAdapter()
{
public void WindowClosing(WindowEvent e)
{
System.exit(0); //这里点窗口上面的X关闭不掉 退出保存 打开按钮都可以做相关动作
}
});
}
public static void main(String[] args)
{
new MyMenuTest();
}
}
|
|