Adding file to jlist

532 Views Asked by At

Adding file to jlist, I add to jframe, one jbutton, one jtextview and one jlist, I add file .txt but effectlly to jtextview ex: C:/Windows/file.txt

JList.add(JList, null);

But theres something went wrong

Thank

1

There are 1 best solutions below

5
DevilsHnd - 退した On

You need to work with the List Model for your JList. You can't just directly add to a JList like you've done since the JList is so versatile to handle all sorts of Objects. It's a little more complicated than that.

First you want to make sure your JList actually contains a Default List Model:

// Make sure the JList contains a List Model
try { 
    DefaultListModel dlm = (DefaultListModel)yourJListName.getModel(); 
}
catch (Exception e) {
    // Nope...so let's set one.
    yourJListName.setModel(new DefaultListModel()); 
}

Now that your sure your JList contains a List Model you can add items to it.

// Get the current List Model for your JList
DefaultListModel dlm = (DefaultListModel)yourJListName.getModel();
// Declare a list to represent it.
JList list = new JList(dlm);
// Get the last position within the List so
// as to append to it.
int pos = list.getModel().getSize();
// Add the text from the JTextField into your JList.
dlm.add(pos, yourJTextFieldName.getText());

Perhaps create a Method to do the adding for you:

public void addToJList(JList yourJList, String stringToAdd) {
    // Make sure the JList contains a List Model
    try { 
        DefaultListModel dlm = (DefaultListModel)yourJList.getModel(); 
    }
    catch (Exception e) {
        // Nope...so let's set one.
        yourJList.setModel(new DefaultListModel()); 
    }

    // Get the current List Model for your JList
    DefaultListModel dlm = (DefaultListModel)yourJList.getModel();
    // Declare a list to represent it.
    JList list = new JList(dlm);
    // Get the last position within the List so
    // as to append to it.
    int pos = list.getModel().getSize();
    // Add the text from the JTextField into your JList.
    dlm.add(pos, stringToAdd);
}

And how you might use it:

addToJList(yourJListName, yourJTextFieldName.getText());