0

例如删除一行时我JTable需要刷新。

我的代码:

@Override
public void actionPerformed(ActionEvent e) {
 if (e.getSource() == dellButton) {
      int selectedRow = table.getSelectedRow();
        if (selectedRow >= 0) {
            try {
                int rowID = (int) table.getValueAt(table.getSelectedRow(), 0);
                int modelRowIndex = table.convertRowIndexToModel(selectedRow);
                rstm.removeRecord(rowID ,rowIndex);
            } catch (SQLException sqle) {
                sqle.printStackTrace();
            }
        } else {
            System.out.println("Select a row");
        }
    }
}
 ....

我的表模型类:

public class ResultSetTableModel extends AbstractTableModel {

private Connection connection;
private Statement statement;
private ResultSet resultSet;
private ResultSetMetaData metaData;
private int numberOfRows;
private boolean connectedToDatabase = false;

public ResultSetTableModel(String driver, String url,
        String username, String password, String query)
        throws SQLException, ClassNotFoundException {

    Class.forName(driver);
    connection = DriverManager.getConnection(url, username, password);
    statement = connection.createStatement(
            ResultSet.TYPE_SCROLL_INSENSITIVE,
            ResultSet.CONCUR_READ_ONLY);

    connectedToDatabase = true;
    updateFromDatabase(query);
}

@Override
public Class getColumnClass(int column) throws IllegalStateException {
    if (!connectedToDatabase) {
        throw new IllegalStateException("Not Connected to Database");
    }

    try {
        String className = metaData.getColumnClassName(column + 1);

        return Class.forName(className);
    } catch (Exception exception) {
        exception.printStackTrace();
    }

    return Object.class;
}

@Override
public int getColumnCount() throws IllegalStateException {
    if (!connectedToDatabase) {
        throw new IllegalStateException("Not Connected to Database");
    }
    try {
        return metaData.getColumnCount();

    } catch (SQLException sqlException) {
        sqlException.printStackTrace();
    }
    return 0;
}

@Override
public String getColumnName(int column) throws IllegalStateException {
    if (!connectedToDatabase) {
        throw new IllegalStateException("Not Connected to Database");
    }
    try {
        return metaData.getColumnName(column + 1);
    } catch (SQLException sqlException) {
        sqlException.printStackTrace();
    }
    return "";
}

@Override
public int getRowCount() throws IllegalStateException {
    if (!connectedToDatabase) {
        throw new IllegalStateException("Not Connected to Database");
    }
    return numberOfRows;
}

@Override
public Object getValueAt(int row, int column)
        throws IllegalStateException {
    if (!connectedToDatabase) {
        throw new IllegalStateException("Not Connected to Database");
    }

    try {
        resultSet.absolute(row + 1);
        return resultSet.getObject(column + 1);
    } catch (SQLException sqlException) {
        sqlException.printStackTrace();
    }

    return "";
}

public void updateFromDatabase(String query)
        throws SQLException, IllegalStateException {
    if (!connectedToDatabase) {
        throw new IllegalStateException("Not Connected to Database");
    }
    resultSet = statement.executeQuery(query);
    metaData = resultSet.getMetaData();

    resultSet.last();                   // move to last row
    numberOfRows = resultSet.getRow();  // get row number      

    fireTableStructureChanged();
}

public void disconnectFromDatabase() {
    if (!connectedToDatabase) {
        return;
    }
    try {
        statement.close();
        connection.close();
    } catch (SQLException sqlException) {
        sqlException.printStackTrace();
    } finally {
        connectedToDatabase = false;
    }
}

public void removeRecord(int userID , int userRow) throws SQLException {
    String deleteQuery = "delete from mytable where id=?";
    PreparedStatement pStatement = connection.prepareStatement(deleteQuery);
    pStatement.setInt(1, userID);
    int rowsAffected = pStatement.executeUpdate();
    System.out.println("Affected rows are: " + rowsAffected);

    fireTableRowsDeleted(userRow,userRow);
}
}

fireTableRowsDeleted()在表模型中使用,但不起作用!

4

1 回答 1

4

我理解你的问题,你认为Deleting a Row from SQL 与JTable 有联系,但实际上并非如此,从SQL 中删除行后,你必须再次设置Jtable 的Model 或者如果你不想设置模型再次通过其方法 .removeRow() 更改 TableModel 这将从该模型中删除行,您的表将自动显示更改。

public class d10 extends JFrame {

DefaultTableModel tableModel = new DefaultTableModel();
Vector<Vector<Object>> doubleVector = new Vector<>();
Vector<Object> singleVector = new Vector<>();
Vector<Object> ColumnNames = new Vector<>();
Connection con = null;
ResultSet rs = null;
PreparedStatement ps = null;
static String dbUrl = "jdbc:mysql://localhost/mydb";
public JTable table;

public static Connection connectToDb() throws ClassNotFoundException, SQLException {
    return DriverManager.getConnection(dbUrl, "root", "2323");
}

public d10() {
    try {
        con = connectToDb();
        ps = con.prepareStatement("select * from mytable");
        rs = ps.executeQuery();

        doubleVector = new Vector<>();
        while (rs.next()) {
            singleVector = new Vector<>();
            singleVector.add(rs.getInt(1));
            singleVector.add(rs.getString(2));
            doubleVector.add(singleVector);
        }
        ColumnNames = new Vector<>();
        ColumnNames.add("ID1");
        ColumnNames.add("Name1");

        tableModel = new DefaultTableModel(doubleVector, ColumnNames);
        table = new JTable(tableModel);

        add(new JScrollPane(table), BorderLayout.CENTER);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 500);
        setLocation(400, 120);
        setVisible(true);

    } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
    } catch (SQLException sqle) {
        sqle.printStackTrace();
    }
}
于 2013-07-27T01:38:52.230 回答