Error with setSelectedValue method for a JLIST
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开发者_Go百科 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 :)
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.
Instead of
JList tablas = new JList(model);
write
tablas = new JList(model);
You create local instance but then use class field in setter.
精彩评论