Java Swing How to - Load a TXT File into a JList








Question

We would like to know how to load a TXT File into a JList.

Answer

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Vector;
//from  ww w  .  j  ava 2 s. c  o m
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;

public class Main {

  public static void main(String[] args) throws Exception {
    File archivo = new File("c:/Java_Dev/run.bat");
    FileReader fr = new FileReader(archivo);
    BufferedReader br = new BufferedReader(fr);

    Vector<String> lines = new Vector<String>();

    String line;
    while ((line = br.readLine()) != null) {
      lines.add(line);
    }
    JOptionPane.showMessageDialog(null, new JScrollPane(new JList(lines)));
    fr.close();
  }
}