简体   繁体   中英

How to load a TXT File into a JList?

I have the following Java code to read a txt file:

    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();
         }
      }
   }

But I need to load that info into a JList , so this JList would show me what words I have saved in the file. Does anyone knows how to do that?

Source

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();
            }
        }
    }
}

Screen shot

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM