如何将TXT文件加载到JList中?

时间:2011-05-08 21:02:52

标签: java swing file-io jlist

我有以下Java代码来读取txt文件:

    class ReadFile {
        public static void main(String [] args) {
        File archivo = null;
        FileReader fr = null;
        BufferedReader br = null;

      try {
         archivo = new File ("C:\\archivo.txt");
         fr = new FileReader (archivo);
         br = new BufferedReader(fr);

         String line;
         while((line=br.readLine())!=null)
            System.out.println(line);
      }
      catch(Exception e){
         e.printStackTrace();
      }finally{
         try{                    
            if( null != fr ){   
               fr.close();     
            }                  
         }catch (Exception e2){ 
            e2.printStackTrace();
         }
      }
   }

但是我需要将该信息加载到JList,因此JList会显示我在文件中保存了哪些字词。有谁知道怎么做?

1 个答案:

答案 0 :(得分:1)

来源

import java.io.*;
import javax.swing.*;
import java.util.Vector;

class ReadFile {

    public static void main(String [] args) {
        File archivo = null;
        FileReader fr = null;
        BufferedReader br = null;

        try {
            archivo = new File ("ReadFile.java");
            fr = new FileReader (archivo);
            br = new BufferedReader(fr);
            // normally I would prefer to use an ArrayList, but JList
            // has a constructor that takes a Vector directly.
            Vector<String> lines = new Vector<String>();

            String line;
            while((line=br.readLine())!=null) {
                System.out.println(line);
                lines.add(line);
            }

            JOptionPane.showMessageDialog(null, new JScrollPane(new JList(lines)));
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            try{
                if( null != fr ) {
                    fr.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
}

屏幕截图

enter image description here