简体   繁体   中英

Populate a jlist from text file read through button

在此处输入图片说明

Code:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

JFileChooser fileChooser = new JFileChooser();
//fileChooser.setCurrentDirectory(new     File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) 

{
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: " + selectedFile.getAbsolutePath());
DefaultListModel lista = new DefaultListModel();
JList jList1 = new JList();

try {
        FileReader archivo = new     FileReader(selectedFile.getAbsolutePath());
        BufferedReader lector = new BufferedReader(archivo);
        String texto = null;
        while ((texto = lector.readLine()) != null) {
            lista.addElement(texto);
            //System.out.println("Lista:"+lista);
            //System.out.println(texto);
        }

        jList1.setModel(lista);
        System.out.println("jList1:"+jList1);

    } 

catch (FileNotFoundException e) {
        e.printStackTrace();
    } 

catch (IOException e) {
        e.printStackTrace();
    } 

}    

}                                        

I am trying to Populate a jlist from text file read through Read_file button

I am able to fetch the file path and the contents of the file correctly which I validated with a print statement, but still my jlist remains empty. In the design, I checked the variable name of the jlist, both matches what I have used in the code.

Please suggest me on the mistake.

From what i see you create a new JList each time you hit the button. You do properly fill the DefaultListModel but you assigned to some jList not to the one you have on your UI.

Just clear the line :

JList jList1 = new JList(); 

then repaint and revalidate it's container after setModel

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