我在从JTable(在视图中)中分离表模型(模型中)时出现问题,我的模型包含从数据库与buildTableModel()
方法:在MVC体系结构中将数据从DefaultTableModel获取到JTable
Model.java
public static DefaultTableModel buildTableModel(ResultSet rs)
throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
//queries to execute for Jtable model listProduit
public ResultSet productList()throws SQLException{
ResultSet rs = stmt.executeQuery("SELECT * from Lot");
return rs;
}
View.java
public class View extends JPanel{
public DefaultTableModel dt;
public JTable productTable;
private JScrollPane scrolPane;
public ListProduit(){
productTable=new JTable(dt);
this.setLayout(new GroupLayout(this));
this.setBackground(Color.decode("#CFDBC5"));
productTable.setPreferredScrollableViewportSize(new Dimension(500,50));
productTable.setFillsViewportHeight(true);
scrolPane= new JScrollPane(productTable);
this.add(scrolPane);
this.setVisible(true);
}
//setter for the table model
public void setDt(DefaultTableModel dt) {
this.dt = dt;
this.dt.fireTableDataChanged();
}
这是部分在那里,我发现了问题:
Controller.java
try{ //lines of the problem:
ResultSet rs= model.productList();
DefaultTableModel dtm = Model.buildTableModel(rs);
View.setDt(dtm);
// Stuff to handle showing the view
showFourthCard();
panelList.add(4);
}catch(SQLException ex){
ex.printStackTrace();
}
Apparentlly当我JTable
不能改变DefaultTbaleModel
对象,它会在第一时间使正在执行我总是得到一个空白的JTable,所以总之我不能在我的Controller.java
中设置一个新的DefaultTableModel
对象。
注:这个时候我不使用MVC
(因为我没有设置表型号)工作得很好,所以我在这里的问题主要是JTable中从表型号分离。