日期:2014-05-20  浏览次数:20854 次

如何将JfileChooser中选取的txt文件显示在JtextArea中
package try;


//AWT: FileDialog类 + FilenameFilter类 可以实现本功能
//Swing: JFileChooser类 + FileFilter类     可以实现本功能

//
//该类用来测试打开文件和保存文件的对话框  

import java.awt.*;      //为了使用布局管理器  
import java.awt.event.*;//用来处理事件  

import javax.swing.*;   //最新的GUI组件  

import java.io.*;       //读写文件用  

public class try1   
{   

  private JFrame frm;   
  private JButton open;   
  private JButton read;   
  private JPanel p;   
  private File f;   
  private JFileChooser fc;   
  private int flag;   

 public  guji1()   
  {   
    frm=new JFrame("显示text");   
    open=new JButton("打开");   
    read=new JButton("保存");   
    p=new JPanel();   
    fc=new JFileChooser();   


    Container c=frm.getContentPane();   
    c.setLayout(new FlowLayout());   

    c.add(p);   
    p.add(open);   
    p.add(read);  
    
    JTextArea t=new JTextArea(12,40);
    c.add(t);
    t.setText(null);
  //注册按钮事件  
    open.addActionListener(new action());   
    read.addActionListener(new action());   
    Toolkit tk=Toolkit.getDefaultToolkit();
    Dimension d=tk.getScreenSize();
    frm.setSize((int)d.getWidth(),(int)d.getHeight());
    //frm.setSize(300,300);   
    frm.setVisible(true);   
  //设置默认的关闭操作  
    frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     
  }   


public void openFile()  //打开文件  
         {   
            //设置打开文件对话框的标题  
              fc.setDialogTitle("Open File");   

            //这里显示打开文件的对话框  
         try{    
                     flag=fc.showOpenDialog(frm);    
              }   
         catch(HeadlessException head){    

                     System.out.println("Open File Dialog ERROR!");   
              }   
               
            //如果按下确定按钮,则获得该文件。  
            if(flag==JFileChooser.APPROVE_OPTION)   
              {   
                   //获得该文件  
                     f=fc.getSelectedFile();   
                     System.out.println("open file----"+f.getName());   
               }   
         }   


private void readFile()//保存文件  
       {   
           String fileName;   

         //设置保存文件对话框的标题  
           fc.setDialogTitle("Save File");    

         //这里将显示保存文件的对话框  
      try{