1

I am trying to create my first list, and I am stuck on an error.

Here is the template I am using for the list model:

    private ListModel getListModel() {

    String[] arrayOfStrings = new String[3];
    arrayOfStrings[0] = "one";
    arrayOfStrings[1] = "two";
    arrayOfStrings[2] = "three";

    ListModel listModel = new DefaultListModel();

    for (int i=0;i<arrayOfStrings.length;i++) {
        listModel.addElement(arrayOfStrings[i]);            
    }   
}    

The error:

error: cannot find symbol
            listModel.addElement(arrayOfStrings[i]);            

symbol:   method addElement(String)

  location: variable listModel of type ListModel

I am still new to using interfaces as well as lists. I downloaded an example code for making a list, and their code was very similar. What am I missing? I imported every single thing that the example code imported.

Matt Groth
  • 470
  • 4
  • 20
  • addElement() is a method of DefaultListModel, which is not present in the ListModel interface. So, to be able to use it, your variable must be declared wit the type DefaultListModel, not ListModel. Also, don't use raw types: http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it. Use DefaultListModel. – JB Nizet Dec 22 '16 at 21:43

2 Answers2

6

When in doubt, go to the API as it will show all. In this situation, the API will show you that the interface, ListModel<E> doesn't have an addElement(...) method. You're going to have to declare the variable as a DefaultListModel<E> type, since that is the implementation that has this method.

References:

Having said this, your method could still return a ListModel interface type... e.g.,

// method declared to return the interface, ListModel
private ListModel<String> getListModel() {
    String[] arrayOfStrings = {"one", "two", "three"};

    // make sure to use generic types
    DefaultListModel<String> listModel = new DefaultListModel<>();
    for (String txt : arrayOfStrings) {
        listModel.addElement(txt);
    }
    return listModel; // don't forget to return a result
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
5

The function addElement(...) is declared in DefaultListModel, but not in ListModel, so it can only be called on an object declared as DefaultListModel.

Use DefaultListModel listModel = new DefaultListModel(); to fix your code.

C. L.
  • 571
  • 1
  • 8
  • 26