一个java写的文件查看程序

来源:互联网 发布:qq表情软件解压软件 编辑:程序博客网 时间:2024/06/04 06:20

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class MyReader implements ActionListener{
 private JFrame f;
 private TextArea ta;
 JDialog dialog ;
  FileDialog fd;
 public MyReader() {
   f = new JFrame("文本文件查看器---无聊的云");
  MenuBar mb = new MenuBar();
  Menu m1 = new Menu("文件");
  MenuItem m11 = new MenuItem("打开");
  MenuItem m12 = new MenuItem("退出");
  m11.setActionCommand("open");
  m12.setActionCommand("exit");
  m11.addActionListener(this);
  m12.addActionListener(this);  
  m1.add(m11);
  m1.addSeparator();
  m1.add(m12);
  Menu m2 = new Menu("帮助");
 MenuItem m21 = new MenuItem("使用方法及说明");
  m21.setActionCommand("help");
  m21.addActionListener(this);
  m2.add(m21);
  mb.add(m1);
  mb.add(m2);
  f.setMenuBar(mb);
  
  ta = new TextArea();
  f.add(ta);
  f.addWindowListener(new WindowAdapter(){
   public void windowClosing(WindowEvent e){
    System.exit(1); 
   } 
  });
        f.setSize(500,400);      //设置窗口大小
        f.setLocation(250,200);    //初始窗口位置
        f.setResizable(false);     //窗口不可调节
        f.setVisible(true);
 }

 public void actionPerformed(ActionEvent e){
  String s = e.getActionCommand();
  if (s.equals("help")) {
         dialog=new JDialog(f,"帮助说明",true);
                       JLabel l=new JLabel("本软件是本人学习的例子,请大家多多提议",JLabel.CENTER);

         dialog.add(l);
          dialog.setSize(300,150);
                        dialog.setLocation(350,300);
                        dialog.setVisible(true);                          
                }
               if (s.equals("open")) {
   fd=new FileDialog(f,"文件对话框",FileDialog.LOAD);
   fd.setVisible(true);
   String fpath = fd.getDirectory();
   String fname = fd.getFile();
   String file = fpath + fname;
   this.outputFile(file);   
  }else if(s.equals("exit")){
   System.exit(1);
  }  
 }

 public void outputFile(String file){
  try {
   FileReader fr = new FileReader(file);
   BufferedReader br = new BufferedReader(fr);
   String d = br.readLine();
    ta.append("……………………文件开始打开……………………");
     ta.append("/n");
   while(d!=null){
     ta.append("/n");
    ta.append(d); //在ta原文本的结尾追加,而非覆盖
    ta.append("/n");//输出一个换行符          
    d = br.readLine(); 
   } 
    ta.append("/n");
    ta.append("……………………文件打开完毕……………………");
   br.close();
   f.setTitle(file);
  }catch (FileNotFoundException e1){
   e1.printStackTrace(); 
  }catch (IOException e2){
   e2.printStackTrace();
  }  
 }

 public static void main(String args[]) {
  new MyReader();
 }

原创粉丝点击