黑马程序员技术交流社区
标题:
分享个简单记事本代码
[打印本页]
作者:
梦里听传说
时间:
2014-9-9 11:58
标题:
分享个简单记事本代码
本帖最后由 付江涛 于 2014-9-9 12:06 编辑
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class TextDemo1
{
public static void main(String[] args)
{
new text();
}
}
class text
{
private Frame ck;
private TextArea wbk;
private MenuBar cdlan;
private File fi;
private Menu cd;
private MenuItem zcd1;
private MenuItem zcd2;
private MenuItem zcd3;
private MenuItem zcd4;
private FileDialog dk;
private FileDialog bc;
text()
{
textck();
}
private void textck()
{
ck=new Frame("我的记事本");
wbk=new TextArea(40,50);
cdlan=new MenuBar();
cd=new Menu("文件");
zcd1=new MenuItem("打开");
zcd2=new MenuItem("保存");
zcd3=new MenuItem("另存为");
zcd4=new MenuItem("关闭");
bc=new FileDialog(ck,"保0存",FileDialog.SAVE);
dk=new FileDialog(ck,"打0开",FileDialog.LOAD);
ck.setMenuBar(cdlan);
ck.add(wbk);
cdlan.add(cd);
cd.add(zcd1);
cd.add(zcd2);
cd.add(zcd3);
cd.add(zcd4);
ck.setBounds(200,100,500,600);
event();
ck.setVisible(true);
}
private void event()
{
ck.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){
System.exit(0);}});
zcd1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){
dk.setVisible(true);
String s1=dk.getFile();
String s2 =dk.getDirectory();
//System.out.println(s1+":::"+s2);
if (s2==null || s1==null)
{
return;
}
BufferedReader buf=null;
File f=new File(s2+s1);
try
{
buf=new BufferedReader(new FileReader(f));
String str=null;
wbk.setText("");
while ((str=buf.readLine())!=null)
{
wbk.append(str+"\r\n");
}
}
catch (IOException a)
{
throw new RuntimeException("读取失败");
}
finally
{
try
{
buf.close();
}
catch (IOException c)
{
throw new RuntimeException("关闭失败");
}
}
}});
zcd3.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){
bc.setVisible(true);
String s1=bc.getFile();
String s2=bc.getDirectory();
if (s2==null||s1==null)
{
return;
}
fi=new File(s2+s1);
BufferedWriter buf=null;
try
{
buf=new BufferedWriter(new FileWriter(fi));
String s=wbk.getText();
buf.write(s);
}
catch (IOException c)
{
throw new RuntimeException("写入失败");
}
finally
{
try
{
buf.close();
}
catch (IOException d)
{
throw new RuntimeException("关闭失败");
}
}
}});
zcd2.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){
BufferedWriter buf=null;
if (fi==null)
{
bc.setVisible(true);
String s1=bc.getFile();
String s2=bc.getDirectory();
if (s2==null||s1==null)
{
return;
}
fi=new File(s2+s1);
}
try
{
buf=new BufferedWriter(new FileWriter(fi));
String s=wbk.getText();
buf.write(s);
}
catch (IOException c)
{
throw new RuntimeException("写入失败");
}
finally
{
try
{
buf.close();
}
catch (IOException d)
{
throw new RuntimeException("关闭失败");
}
}
}});
}
}
复制代码
作者:
付江涛
时间:
2014-9-9 12:05
V字仇杀队
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2