0

下面是我从数据库创建表的代码。我想在最后添加一个不会在数据库中的复选框列。它只是前端的一部分。你能帮忙吗?

尽管选择了一行,但我的 getRow() 方法继续返回-1,有什么建议吗?

  package Default;
 import javax.swing.*;
 import javax.swing.event.ListSelectionEvent;
 import javax.swing.event.ListSelectionListener;
import javax.swing.table.*;
 import java.sql.*;

/**
 * This class create JTable from Database table.
 * User program needs to specify database connection and corresponding a table name.
 * 
 */

public class DBTable{
//private String table;

DefaultTableModel dm=new DefaultTableModel();
JTable t1=new JTable();
Object row[];
String c[];
int cols;
PreparedStatement pst;
ResultSet rs  ;  

public DBTable(Connection conn){
   conn=Login.con;
}

/**
* This method return JTable object created from Database table having selected data and structur     * as in original table into database.
* @param table Name of the database table to be coverted to JTable
* @param query Select query to specify selected columns and data to extracted from database table
* @return JTable object that consist of selected data and structure of Database table
* @throws java.lang.Exception Original object is deferent, e.i either SQLException or NullPointerException
*/

public JTable getTable(String table,String query)throws Exception{

    JTable t1=new JTable();
    DefaultTableModel dm=new DefaultTableModel();
    Statement st= Login.con.createStatement();
    ResultSet rs=st.executeQuery(query);
    ResultSetMetaData rsmd=rs.getMetaData();
    //Coding to get columns-
    int cols=rsmd.getColumnCount();
    String c[]=new String[cols];
    for(int i=0;i<cols;i++){
        c[i]=rsmd.getColumnName(i+1);
        dm.addColumn(c[i]);
    }



    //get data from rows
    Object row[]=new Object[cols];
    while(rs.next()){
         for(int i=0;i<cols;i++){
                row[i]=rs.getString(i+1);
            }
        dm.addRow(row);
    }
    t1.setModel(dm);


    return t1;
}


      public int getRow(){

 int row =   t1.getSelectedRow();
JOptionPane.showMessageDialog(null, row);

    return  row; 
}

public void deleteRow(String sql){

try {
    String value = (String) t1.getValueAt(getRow(), 0);
    JOptionPane.showMessageDialog(null, value);
    pst = Login.con.prepareStatement(sql);
    pst.setString(1,  value);
    ((DefaultTableModel)t1.getModel()).removeRow(getRow());
    pst.execute();
    JOptionPane.showMessageDialog(null, "Deleted");


   } catch (Exception e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(null, e);
     }
}
}
4

1 回答 1

1

您使用的是 DefaultTableModel,因此在创建模型后,您可以手动添加一列:

model.addColumn("CheckBox Column");
于 2013-03-15T15:53:09.767 回答