我有一个按钮,它只读取数据库表中的所有字段(从电影中选择*),因此我使用AbstractTableModel
。第一个表用这个类读取OK,但是如果我为其他表实现AbstractTableModel
我得到了NPE。
这是我的代码TableModelForMovies
:
package ua.movies.movie;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
public class TableModelForMovies extends AbstractTableModel {
private static final int NAME_COL = 0;
private static final int Genre_COL = 1;
private static final int Release_Date = 2;
private static final int Unique = 3;
private String[] columnNames = { "name", "genre",
"release" , "dgdggdf" };
private List<Movie> movies;
public TableModelForMovies(List<Movie> theMovie) {
movies = theMovie;
}
@Override
public int getRowCount() {
return movies.size(); <<- here is problem
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public String getColumnName(int col) {
return columnNames[col];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Movie tmpMovie = movies.get(rowIndex);
switch (columnIndex) {
case NAME_COL:
return tmpMovie.getMovieName();
case Genre_COL:
return tmpMovie.getGenre();
case Release_Date:
return tmpMovie.getRelease();
case Unique:
return tmpMovie.getUniqueKey();
default:
return tmpMovie.getMovieName();
}
}
}
和我的按钮上的听众
try {
String movieName = textFindField.getText();
List<Movie> employees = null;
if (movieName != null && movieName.trim().length() > 0) {
//employees = movieDao.search(lastName);
employees = movieDao.getAllMovies();
} else {
searchByName();
}
// create the model and update the "table"
TableModelForMovies model = new TableModelForMovies(employees);
tableMovies.setModel(model);
} catch (Exception exc) {
JOptionPane.showMessageDialog(AppMovies.this, "Error: " + exc, "Error", JOptionPane.ERROR_MESSAGE);
}
我真的不明白为什么我会得到NPE。因为我有第二类,它也扩展AbstractTableModel
并且没有任何错误,NPE就在这里。
答案 0 :(得分:0)
有可能在getRowCount()
列表初始化之前调用movies
方法,当您覆盖getRowCount()
方法时,请使用以下模式:
@Override
public int getRowCount()
{
int result = 0;
synchronized(LOCK) {
if(movies != null) {
result = movies.size();
} // if
} // synchronized
return result;
}