简体   繁体   中英

Updating list with files (Java swing)

So, I have this code in my JFrame, and it doesn't work for some reason:

private void jList1MouseEntered(java.awt.event.MouseEvent evt) {                                    
        DefaultListModel jList1Model = (DefaultListModel) jList1.getModel();
        File f=new File("/home");
        File[] allSubFiles=f.listFiles();
        for (File file : allSubFiles) {
            jList1Model.addElement(file.getAbsolutePath());
        }
    }

What am I doing wrong (ignore MouseEntered event, I'll change it)? It doensn't update anything when I hover over the active this list.

because It gives me an exception javax.swing.JList$3 cannot be cast to javax.swing.DefaultListModel

Don't you think that was an important piece of missing information from the question?

So basically that means you need to create your JList with code like:

DefaultListModel<String> model = new DefaultListModel<String>();
JList<String> list = new JList<String)(model);

Now you can dynamically try to add data to the model.

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