2013-07-26 6 views
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() Я использую в таблице модели, но не работает!

+2

Вы звоните fireTableRowsDeleted(), чтобы сообщить мнению о том, что строка была удалена, но не удалить все строки из модели таблицы: строка не действительно была удалена из модели. Кроме того, вызов notify() не имеет никакого смысла. А также индексы строк в представлении (JTable) не обязательно совпадают с индексами строк в модели. Используйте JTable.convertRowIndexToModel(). –

+0

@JBNizet Что вы имеете в виду? Я удаляю строку 'deleteQuery' в моей базе данных – Sajad

+1

JTable не считывает свои строки из базы данных. Он считывает свои строки из TableModel. –

ответ

4

Я понял вашу проблему, вы думаете, что удаление строки из SQL имеет соединение с JTable, но на самом деле это не так, после удаления строки из SQL вам нужно снова установить модель Jtable или если вы не наденете, t хотите снова установить модель, просто измените 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(); 
    } 
} 
+0

Можете ли вы сказать свое решение с моим кодом? – Sajad

+0

проблема в том, что вы используете очень сложный код, работа, которую вы пытаетесь, очень проста, всего несколько строк кода без создания нового класса. Если вы хотите, я могу дать вам код, из которого вы можете удалить строки из SQL, а также из таблицы, но с помощью вашего кода очень сложно. – JProgrammer

+0

Я жду вашего кода ... – Sajad