JAVA 记事本的实现

import java.awt.BorderLayout;

import java.awt.Dimension;

import java.awt.FileDialog;

import java.awt.FlowLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import javax.swing.JFrame;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.JMenuItem;

import javax.swing.JPanel;

import javax.swing.JTextArea;

public class dem3 extends JFrame implements ActionListener

{

JPanel jp1, jp2;

JTextArea jTextArea;

JMenuBar jMenubar;

JMenu jMenu;

JMenuItem jm1, jm2;

public static void main(String[] args)

{

// TODO 自动生成的方法存根

dem3 dem3 = new dem3();

}

public dem3()

{

jp1 = new JPanel();

jp2 = new JPanel();

jTextArea = new JTextArea();

jTextArea.setPreferredSize(new Dimension(280, 300));

jMenubar = new JMenuBar();

jMenu = new JMenu("开始");

jm1 = new JMenuItem("打开");

jm2 = new JMenuItem("保存");

jMenu.add(jm1);

jMenu.add(jm2);

jMenubar.add(jMenu);

jm1.addActionListener(this);

jm1.setActionCommand("打开");

jm2.addActionListener(this);

jm2.setActionCommand("保存");

this.add(jp1, BorderLayout.NORTH);

jp1.setLayout(new FlowLayout(FlowLayout.LEFT));

jp1.add(jMenubar);

this.add(jp2, BorderLayout.CENTER);

jp2.add(jTextArea);

this.setSize(300, 400);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.setVisible(true);

}

@Override

public void actionPerformed(ActionEvent e)

{

// TODO 自动生成的方法存根

if (e.getActionCommand() == "打开")

{

FileDialog file_open = new FileDialog(this, "打开文件", FileDialog.LOAD);

file_open.setVisible(true);

FileReader fReader = null;

BufferedReader bReader = null;

try

{

String filepath = file_open.getDirectory() + "//" + file_open.getFile();

fReader = new FileReader(filepath);

bReader = new BufferedReader(fReader);

String str = "";

String strtext = "";

while ((str = bReader.readLine()) != null)

{

strtext = strtext + str + "\r\n";

}

jTextArea.setText(strtext);

} catch (Exception e2)

{

// TODO: handle exception

} finally

{

try

{

bReader.close();

fReader.close();

} catch (IOException e1)

{

// TODO 自动生成的 catch 块

e1.printStackTrace();

}

}

} else

{

FileDialog file_save = new FileDialog(this, "保存文件", FileDialog.SAVE);

file_save.setVisible(true);

FileWriter fWriter = null;

BufferedWriter bWriter = null;

try

{

String strpath = file_save.getDirectory() + "//" + file_save.getFile();

fWriter = new FileWriter(strpath);

bWriter = new BufferedWriter(fWriter);

String strtext = jTextArea.getText();

bWriter.write(strtext);

} catch (Exception e2)

{

// TODO: handle exception

} finally

{

try

{

bWriter.close();

fWriter.close();

} catch (IOException e1)

{

// TODO 自动生成的 catch 块

e1.printStackTrace();

}

}

}

}

}

你可能感兴趣的:(JAVA 记事本的实现)