import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
/**
*
Title:java -简易文本编辑器
*
*
Description: 08.5.5 简易功能
* 1。 打开文件时,无法选择文件,需手动输入
* 2. 文件大小超出 多行文本域时,未实现滚动 *
*
*
Copyright: Copyright (c) 2008
*
*
Company:
*
* @author not attributable
* @version 1.0
*/
public class Eidter implements ActionListener{
JFrame f;
JMenuItem menuItemOpen,menuItemSave,menuItemQuit;
JTextArea jtTet;
String directory = "E://";
String fileName="";
public Eidter() {
f = new JFrame("无标题-记事本");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setJMenuBar(createJMenuBar());
jtTet = new JTextArea(25,40);
f.getContentPane().add(jtTet);
f.setSize(500,500);
f.setDefaultLookAndFeelDecorated(true);
f.setVisible(true);
}
public JMenuBar createJMenuBar(){
JMenuBar file = new JMenuBar();
JMenu begin = new JMenu("文件");
menuItemOpen= new JCheckBoxMenuItem("打开");
begin.add(menuItemOpen);
menuItemSave = new JCheckBoxMenuItem("保存");
begin.add(menuItemSave);
menuItemQuit = new JCheckBoxMenuItem("退出");
begin.add(menuItemQuit);
menuItemOpen.addActionListener(this);
menuItemSave.addActionListener(this);
menuItemQuit.addActionListener(this);
file.add(begin);
return file;
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == menuItemOpen){
jtTet.setText(" ");
String[] text = new String[256];
int i=0;
try{
fileName=JOptionPane.showInputDialog(null,"请输入文件名","打开",JOptionPane.YES_NO_CANCEL_OPTION);
File openFile = new File(fileName);
if(! openFile.exists()){
JOptionPane.showMessageDialog(null,"文件不存在!");
}
else
{
f.setTitle(fileName+"--记事本");
BufferedReader in = new BufferedReader(new FileReader(openFile));
while((text[i]=in.readLine())!=null){
jtTet.append(text[i]);
jtTet.append("/n");
i++;
}
in.close();
}
}catch(IOException ex){
System.out.println("io exception!");
}
}
if(e.getSource() == menuItemSave){
if(fileName.length() == 0){ try{ File openFile = new File("E://未命名.txt"); BufferedWriter out = new BufferedWriter(new FileWriter( openFile)); out.write(jtTet.getText()); out.close(); }catch(IOException ex){ System.out.println("io exception!"); } } else { try{ File openFile = new File(fileName); BufferedWriter out = new BufferedWriter(new FileWriter( openFile)); out.write(jtTet.getText()); out.close(); }catch(IOException ex){ System.out.println("io exception!"); } } } if(e.getSource() == menuItemQuit){ System.exit(0); } } public static void main(String[] args) { Eidter f = new Eidter(); }