不多说,直接上代码:
package Note;
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.Window;
import java.awt.event.*;
import java.io.*;
import javax.swing.JTextArea;
public class Note extends java.applet.Applet{
public static void main(String args[]) {
Note a = new Note();
a.note();
}
public void note(){
//创建框架
Frame f = new Frame("山寨记事本");
f.setSize(500,500);
f.setVisible(true);
//菜单选项
MenuBar mb = new MenuBar();
f.setMenuBar(mb);
Menu fm = new Menu("文件");
mb.add(fm);
MenuItem creat = fm.add(new MenuItem("新建"));
MenuItem open = fm.add(new MenuItem("打开"));
MenuItem save = fm.add(new MenuItem("保存"));
Menu opt = new Menu("编辑");
mb.add(opt);
MenuItem modtitle = opt.add(new MenuItem("自动换行"));
Menu help = new Menu("帮助");
mb.add(help);
mb.setHelpMenu(help);
//创建文本域
JTextArea txt = new JTextArea();
f.add(txt);
//退出
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
e.getWindow().setVisible(false);
((Window)e.getComponent()).dispose();
System.exit(0);
}
});
//保存
save.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==save){
//第一种保存方法,网上找的,界面不好看
// JFileChooser chooser=new JFileChooser();
// int result=chooser.showSaveDialog(txt);
// try{
// FileWriter fout = new FileWriter(chooser.getSelectedFile());
// fout.write(txt.getText()+"\r\n");
// fout.close();
// }catch(IOException ioex)
// {
// System.err.println(ioex);
// }
//第二种保存方法,自己写的
FileDialog fd = new FileDialog(f,"保存",FileDialog.SAVE);
fd.setVisible(true);
String dirpath = fd.getDirectory();//获取保存文件路径并保存到字符串中
String fileName = fd.getFile();获取打保存文件名称并保存到字符串中
try{
FileOutputStream wf = new FileOutputStream(dirpath+fileName+".txt",true); //保存
String s = txt.getText()+"\r\n"; //获取文本域字符串
byte[] t = s.getBytes(); //将字符串改为字节
wf.write(t); //写入文件
wf.close();
}catch(IOException ioe){
System.out.println(ioe);
}catch (Exception e1) {
System.out.println(e1);
}
}
}
});
//打开
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==open){
FileDialog df = new FileDialog(f,"保存",FileDialog.LOAD);
df.setVisible(true);
String dirpath = df.getDirectory();//获取打开文件路径并保存到字符串中
String fileName = df.getFile();//获取打开文件名称并保存到字符串中
if (dirpath == null || fileName == null)//判断路径和文件是否为空
return;
else
txt.setText(null);//文件不为空,清空原来文件内容(试了下好像没作用)
try{
BufferedReader re = new BufferedReader(new FileReader(dirpath+fileName));//读取文件
String line = null;
while((line=re.readLine())!=null){ //写入文本域
txt.append(line+"\r\n");
}
re.close();
}catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
//帮助,还没写好不写了,要期末考试了
help.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==help){
System.out.println("help");
}
}
});
}
}