使用DbUtils将ResultSet转换为TableModel后,JTable将设置为可编辑。如何让它再次不可编辑?

时间:2014-09-19 23:04:51

标签: java swing jtable tablemodel

这是我执行此操作的代码

public static void addSong(String[] fileDetail, JTable SongData_Table)
{
    try {
        con = DBConnection.getCon();
        stmt = con.createStatement();

        stmt.executeUpdate("insert into songs values (null,'" + fileDetail[0] + "', '" + fileDetail[1] + "',null,null)");
        ResultSet rs = stmt.executeQuery("select * from songs");

        TableModel model = DbUtils.resultSetToTableModel(rs);
        SongData_Table.setModel(model);

        if (con != null) {
            stmt.close();
            con.close();
        }
    } catch (SQLException e) {
        System.out.println("Error in Stmt " + e);
    }
}

4 个答案:

答案 0 :(得分:2)

DbUtils.resultSetToTableModel中,替换

return new DefaultTableModel(rows, columnNames);

并返回覆盖TableModel的<{1}}:

isCellEditable()

答案 1 :(得分:2)

变量名称不应以大写字符开头。 SongData_Table应为songDataTable

覆盖JTable的isCellEditable(...)方法,而不是TableModel。

JTable songDataTable = new JTable()
{
    @Override boolean isCellEditatable(int row, int column)
    {
        return false;
    }
};

答案 2 :(得分:0)

您可以覆盖方法isCellEditable:

 //instance table model
  DefaultTableModel tableModel = new DefaultTableModel() {

  @Override
  public boolean isCellEditable(int row, int column) {
   //all cells false
   return false;
   }
 };

  table.setModel(tableModel);

...或

  table.setEnabled(false);

答案 3 :(得分:0)

改为使用Vector将ResultSet转换为TableModel:

.......    
Vector column = new Vector();
column.addElement("Columnname1");
column.addElement("Columnname2");
column.addElement("Columnname3");
........
//data Vector
Vector data = new Vector();
while (rs.next()) {
Vector temp = new Vector();
temp.addElement(rs.getString(1));
temp.addElement(rs.getString(2));
 temp.addElement(rs.getString(3));
  ........      
data.addElement(temp);
}
//append to JTable
yourtable.setModel(new javax.swing.table.DefaultTableModel(data,column){

@Override
public boolean isCellEditable(int row, int column) {
   return false;
}
});
......