Reputation: 11
I am having troubles with JList class. I am getting data from a vector to fill the JList and the list looks fine when I show it on screen. The list contains table names,and the selected one is the table to be displayed. So the proyect structure is based on the getSelectedValue() of the List. When I first run the program getSelectedValue returned null, so I tried modifiying it by myself with setSelectedValue("Alumnos", true) and I get this: Exception in thread "main" java.lang.NullPointerException at interfaz.DataBaseManagerJList.setSelectedValue(DataBaseManagerJList.java:53)
This makes no sense since Alumnos is in the list when I display it on screen. Here is the JList class code:
public class DataBaseManagerJList extends JPanel
{
private static final long serialVersionUID = 1L;
private static JList tablas;
DefaultListModel model;
DatabaseTableManagers dtm = DatabaseTableManagers.getInstance();
private static DataBaseManagerJList instance = null;
public static DataBaseManagerJList getInstance()
{
if (instance == null)
{
instance = new DataBaseManagerJList();
}
return instance;
}
public DataBaseManagerJList()
{
model = new DefaultListModel();
ArrayList<String> aux = new ArrayList<String>(dtm.getTableNames());
for(int i =0;i<aux.size();i++)
{
model.addElement(aux.get(i));
System.out.println(aux.get(i));
}
JList tablas = new JList(model);
//tablas.setSelectedValue("Alumnos",true);
add(tablas);
}
public String devolver()
{
return (String) tablas.getSelectedValue();
}
public void setSelectedValue(String name)
{
tablas.setSelectedValue(name, true);
}
}
Any ideas? Thanks everyone :)
Upvotes: 0
Views: 345
Reputation: 23629
I would guess that the String in your model has a space or some other difference than the one you are trying to select. Instead of hardcoding a value. Try just selecting the first item from the model. For example:
JList tablas = new JList(model);
tablas.setSelectedValue(aux.get(0), true);
add(tablas);
That way you are guaranteed that the value is in the model. (Assuming the list is not empty).
Another advantage is Alumnos is no longer a hardcoded value so that if it is not longer an option in your list you don't have to change the code that selects it.
Upvotes: 3
Reputation: 57421
Instead of
JList tablas = new JList(model);
write
tablas = new JList(model);
You create local instance but then use class field in setter.
Upvotes: 2