JTable填充类的实例

时间:2013-05-01 21:56:06

标签: java swing jtable

我希望用电影填充我的JTable。

我上课Film

public class Film extends MainComponent{
String title;
String year;
String genre;

//director
//actor
public Film(String title, String year, String genre, int id, int stars) {
    super(id, stars);
    this.title = title;
    this.year = year;
    this.genre = genre;
}

public String getTitle() {
    return title;
}

public String getYear() {
    return year;
}

public String getGenre() {
    return genre;
}

@Override
public String toString() {
    return "Film{" + "title=" + title + ", year=" + year + ", genre=" + genre +",id="+getId()+", stars="+getStars()+ '}';
}


}

从DB我读取我的电影记录并创建新的电影实例,然后我将它们传递给矢量。

public ResultSet select(String table, String where) {
    try {       
        Statement sta = con.createStatement(); 
        System.out.println( "SELECT * FROM " + table + " WHERE " + where );
        return sta.executeQuery( "SELECT * FROM " + table + " WHERE " + where );
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
    return null;
}

ResultSet rs;
    Vector<Film> films = new Vector();

    rs = db.select("films");

    try{
        while(rs.next()){
            films.add(new Film(rs.getString("name"), rs.getString("year"), "Action", rs.getInt("id"), 5));
        }
    }catch (SQLException exc){
        System.out.println("Error: " + exc);
    }

任何人都可以帮助我,我怎么能用我的电影填充我的JTable:

|Name|Year|Genre|
=================
|Batman|2010|Action|
...
...

感谢您的回复。

1 个答案:

答案 0 :(得分:0)

前段时间我写了一篇ListTableModel课来解决这个问题。

用法:

ListTableModel ltm = new ListTableModel();
ltm.setModelClass(Film.class);
ltm.setColumnNames(new String[] {"title", "year", "genre"});
ltm.setDisplayNames(new String[] {"Title", "Year", "Genre"});
ltm.setList(getFilmList());

JTable table = new JTable(ltm, ltm.getTableColumnModel());

如果您是使用HibernateJPAIBatis的Spring用户,则可以在bean定义文件中配置该表:

<jdal:service entity="Film" />

<swing:defaults />

<swing:table entity="Film">
    <swing:columns>
        <swing:column name="title" displayName="title" />
        <swing:column name="year"  displayName="Year"  /> 
        <swing:column name="gemre" displayName="Gemre" />  
    </swing:columns>
</swing:table>

TablePanel table = applicationContext.getBean("filmTable", TablePanel.class);

TablePanel添加服务器端分页和排序。