I need help with JList
. Need to add a text file to a list but txt file is named library.txt
with:
title1 author1 description1 publisher1
title2 author2 description2 publisher2
title3 author3 description3 publisher3
title4 author4 description4 publisher4
What program needs to do is to fill list only with titles from txt and when user select certain title from list the program needs to write the description to a JTextArea
.
This is what I got so far.
import java.awt.FlowLayout;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTextArea;
public class Library extends JFrame {
private JList lista;
private JTextArea tekst;
DefaultListModel model;
public Library() {
super("Biblioteka");
this.setSize(300, 300);
setLayout(new FlowLayout());
model = new DefaultListModel();
lista = new JList(model);
add(lista);
tekst = new JTextArea(20, 20);
add(tekst);
File fajl = new File("library.txt");
BufferedReader ulaz = null;
try {
FileReader fr = new FileReader(fajl);
ulaz = new BufferedReader(fr);
String linija;
try {
while ((linija = ulaz.readLine()) != null) {
//lista.add(linija);
//System.out.println(linija);
String[] reci = linija.split("\t");
String naslovi = null;
for (int i = 0; i < reci.length; i++) {
naslovi = reci[0];
}
int pos = lista.getModel().getSize();
model.addElement(naslovi.toString());
}
} catch (IOException ex) {
Logger.getLogger(Library.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Library.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
Library l = new Library();
l.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
l.setSize(300, 430);
l.setVisible(true);
}
}