JTable需要刷新才能显示变化

时间:2013-07-26 22:07:01

标签: java swing jtable

我的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(),但不起作用!

1 个答案:

答案 0 :(得分:4)

我理解你的问题,你认为从SQL删除一行与JTable有连接,但实际上并非如此,在从SQL中删除行之后你必须再次设置Jtable的模型,或者如果你没有想要再次设置模型只需通过其方法更改TableModel .removeRow()这将删除该模型中的行,您的表将自动显示更改。

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();
    }
}