- import java.awt.*;
- import java.awt.event.*;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- public class Test8 {
- private Frame f;
- private MenuBar mb;
- private Menu fileMenu;
- private MenuItem openItem, saveItem, closeItem;
- private FileDialog openDia, saveDia;
- private TextArea ta;
- private File file;
- public Test8() {
- init();
- }
- public void init() {
- f = new Frame("my window");
- f.setBounds(300, 100, 500, 600);
- mb = new MenuBar();
- fileMenu = new Menu("文件");
- openItem = new MenuItem("打开");
- saveItem = new MenuItem("保存");
- closeItem = new MenuItem("退出");
- ta = new TextArea();
- fileMenu.add(openItem);
- fileMenu.add(saveItem);
- fileMenu.add(closeItem);
- mb.add(fileMenu);
- f.setMenuBar(mb);
- f.add(ta);
- openDia = new FileDialog(f, "我要打开", FileDialog.LOAD);
- saveDia = new FileDialog(f, "我要保存", FileDialog.SAVE);
- myEvent();
- f.setVisible(true);
- }
- private void myEvent() {
- saveItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- // TODO Auto-generated method stub
- if (file == null) {
- saveDia.setVisible(true);
- String path = saveDia.getDirectory();// 得到文件夹
- String name = saveDia.getFile(); // 得到文件名字
- if (path == null || name == null) {
- return;
- }
- file = new File(path, name);
- }
- try {
- BufferedWriter bufw = new BufferedWriter(new FileWriter(
- file));
- String text = ta.getText();
- bufw.write(text);
- bufw.close();
- } catch (IOException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- }
- });
- f.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- System.exit(0);
- }
- });
- openItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- // TODO Auto-generated method stub
- openDia.setVisible(true);
- String path = openDia.getDirectory();// 得到文件夹
- String name = openDia.getFile(); // 得到文件名字
- // System.out.println(path+"..."+name);
- if (path == null || name == null) {
- return;
- }
- file = new File(path, name);
- ta.setText("");
- try {
- BufferedReader br = new BufferedReader(new FileReader(file));
- String text = ta.getText();
- String line = null;
- try {
- while ((line = br.readLine()) != null) {
- ta.append(line + "\r\n");
- }
- br.close();
- } catch (IOException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- } catch (FileNotFoundException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- }
- });
- }
- public static void main(String[] args) {
- new Test8();
- }
- }
复制代码 |