import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class FrameDemo2
{
private Frame f;
private TextArea ta;
private MenuBar mb;
private Menu filemenu;
private MenuItem openfile, savefile, exit;
private FileDialog opendialog, savedialog;
private File file;
FrameDemo2()
{
Initialization();
addListener();
}
//-----------------初始化动作
private void Initialization()
{
f = new Frame("My Frame");
f.setBounds(300, 100, 700, 500);
// f.setLayout(new FlowLayout());
f.setVisible(true);
ta = new TextArea();
f.add(ta);
mb = new MenuBar();
f.setMenuBar(mb);
filemenu = new Menu("文件");
openfile = new MenuItem("打开");
savefile = new MenuItem("保存");
exit = new MenuItem("退出");
mb.add(filemenu);
filemenu.add(openfile);
filemenu.add(savefile);
filemenu.add(exit);
}
//------------------添加监听器
private void addListener()
{
//窗口添加监听器
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
//打开menuitem添加监听器
openfile.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
opendialog = new FileDialog(f, "打开文件", FileDialog.LOAD);
opendialog.setBounds(400, 150, 400, 400);
opendialog.setVisible(true);
String dirpath = opendialog.getDirectory();
String filename = opendialog.getFile();
BufferedReader br = null;
if(dirpath != null && filename != null)
try
{
file = new File(dirpath, filename);
br = new BufferedReader(new FileReader(file));
String line = "";
ta.setText("");
while((line = br.readLine()) != null)
{
ta.append(line + "\n");
}
} catch (Exception e2)
{
// TODO: handle exception
}
finally
{
try
{
if(br != null)
br.close();
} catch (Exception e3)
{
e.toString();
}
}
}
});
//保存savefile添加监听器
savefile.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
BufferedWriter bw = null;
if(file == null)
{
savedialog = new FileDialog(f, "打开文件", FileDialog.SAVE);
savedialog.setBounds(400, 150, 400, 400);
savedialog.setVisible(true);
String dirpath = savedialog.getDirectory();
String filename = savedialog.getFile();
file = new File(dirpath, filename);
}
try
{
bw = new BufferedWriter(new FileWriter(file));
String text = ta.getText();
bw.write(text);
}
catch (Exception e2)
{
e2.toString();
}
finally
{
try
{
if(bw != null)
bw.close();
} catch (Exception e3)
{
// TODO: handle exception
}
}
}
});
//退出menuitem添加监听器
exit.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
/**
* @param args
*/
public static void main(String[] args)
{
new FrameDemo2();
// System.out.println(new FrameDemo2().file);
}
}
|
|