1

I have a JList model that wants me to specify the index ("array[i]" not just "array") in my array of strings in order to add it as an element. Otherwise it just returns hash code. How can I add it if it comes from a separate method? The only way I found was to just copy-paste the method's code every time I needed it which doesn't seem like a good solution.

This is where I want to add it:

    DefaultListModel model = new DefaultListModel();
    for (int i = 0; i < fileFinder.thing().length; i++) {
        model.addElement(fileFinder.thing());
    }
    JList list = new JList(model);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    scrollPane.setViewportView(list);

This is what the method looks like:

    public class fileFinder {
    public static String[] thing() {
        File file = new File(".\\at9snfsbs");
        File[] files = file.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                if (name.toLowerCase().endsWith(".at9")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        String[] fileNames = new String[files.length];
        for (int i = 0; i < files.length; i++) {
            fileNames[i] = files[i].getName();
        }

        return fileNames;
    }
}

I'm by no means a good or experienced programmer so any help would be useful!

1 Answer 1

1

Change it to:

DefaultListModel model = new DefaultListModel();
String[] things = fileFinder.thing();
for (String thing : things) {
    model.addElement(thing);
}
JList list = new JList(model);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollPane.setViewportView(list);

You can also use the long version of the for loop like this:

DefaultListModel model = new DefaultListModel();
String[] things = fileFinder.thing();
for (int i = 0; i < things.length; i++) {
    model.addElement(things[i]);
}
JList list = new JList(model);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollPane.setViewportView(list);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.