import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
/**
*
Title:
*
*
Description:
*1。加入文件选择功能
2.实现文件滚动
*
Copyright: Copyright (c) 2008
*
*
Company:
*
* @author not attributable
* @version 1.0
*/
public class Editer implements ActionListener{
JFrame f;
JMenuItem menuItemOpen,menuItemSave,menuItemQuit;
JTextArea jtTet;
String directory = "E://";
String fileName="";
public Editer() {
f = new JFrame("无标题-记事本");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setJMenuBar(createJMenuBar());
jtTet = new JTextArea(25,40);
JScrollPane p = new JScrollPane(jtTet); f.getContentPane().add(p);
f.setSize(500,500);
f.setLocation(200,250);
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{
FileDialog myFileDialog = new FileDialog(new JFrame(),"打开",FileDialog.LOAD);
myFileDialog.setBounds(500,500,FileDialog.WIDTH,FileDialog.HEIGHT);
myFileDialog.setDirectory(directory);
myFileDialog.show();
directory = myFileDialog.getDirectory();
fileName = myFileDialog.getFile();
myFileDialog.dispose();
File openFile = new File(directory,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(directory,"未命名.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(directory,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) { Editer f = new Editer(); }