[英]TableModel - Doesn`t show anything in the gui?
我正在從DAO到GUI級別獲取數據。
當我要加載表時,我得到的空表僅包含單擊的數據庫符號的正確行數:
要加載我使用的元素:
playlistTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 1) {
JTable target = (JTable)e.getSource();
int row = target.getSelectedRow();
playlistTableModel.setPlaylists(playlistService.getMoviesOfPlaylist(row));
}
為什么表為空?
更新
表模型代碼:
public class PlaylistTableModel extends AbstractTableModel {
/**
* Generated UID
*/
private static final long serialVersionUID = 9058516120594137393L;
/**
* List of playlist to be shown
*/
private List<Playlist> playlist;
public PlaylistTableModel(List<Playlist> playlist){
this.playlist=playlist;
}
public int getColumnCount() {
return 1;
}
public int getRowCount() {
return playlist.size();
}
public Object getValueAt(int arg0, int arg1) {
Playlist playlists = playlist.get(arg0);
switch(arg1){
case 0: return playlists.getName();
default: return null;
}
}
public void setPlaylists(List<Playlist> playlist){
this.playlist=playlist;
fireTableDataChanged();//Aktualisiert Playlist automatisch
}
public void setPlaylist(Playlist playlists){
playlist.add(playlists);
fireTableRowsInserted(playlist.size()-1, playlist.size()-1);
}
public String getColumnName(int column) {
if(column==0){
return "Playlist";
}
else{
return null;
}
}
/**
* Returns a movie from the list specified by the index
* @param row index of the movie
* @return movie
*/
public Playlist getPlaylist(int row){
return playlist.get(row);
}
@Override
public boolean isCellEditable(int row, int col) {
return true;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex){
if(columnIndex!=0){
return;
}
fireTableCellUpdated(rowIndex, columnIndex);
}
這種方法可能是個問題,
public void setPlaylist(Playlist playlists){
playlist.add(playlists);
fireTableRowsInserted(playlist.size()-1, playlist.size()-1);
}
例如,在這里,如果我們獲得了大小為20的播放列表,然后將其分配給表模型播放列表后,
fireTableRowsInserted(playlist.size()-1, playlist.size()-1);
減少到
fireTableRowsInserted(19, 19);
但是實際上發生的是,我們不僅要插入一行,還要插入20行。 因此,正如@ Ivan.Latysh在答案部分中建議的那樣 ,您需要從行計數的開始到行計數的結束調用insert。 這將repaint
插入的行。
PS:您可以簡單地調用fireTableDataChanged();
方法也。 但是此方法將repaint
整個表。 僅在更改整個表列表時,才建議使用此方法。 另外,您還有用於插入,更新和刪除的 fireXX
方法。
可能問題是在getValueAt
方法中,像這樣更改
public Object getValueAt(int arg0, int arg1) {
// since you use only one column
return playlist.get(arg0).getName();
}
問題是您觸發了錯誤的變更事件
fireTableRowsInserted(playlist.size()-1, playlist.size()-1);
文件狀態:
public void fireTableRowsInserted(int firstRow,
int lastRow)
Notifies all listeners that rows in the range [firstRow, lastRow], inclusive, have been inserted.
因此,如果您想獲得最佳效果,請執行以下操作:
public void setPlaylist(Playlist playlists){
int firstRow = playlist.size();
playlist.add(playlists);
fireTableRowsInserted(firstRow, playlist.size()-1);
}
或者只是簡單地重新繪制整個表格。 別忘了該表也可能會重新計算其大小。
fireTableDataChanged();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.