Pregunta

As mentioned in the header I cannot get my JTable to update with a new row unless I restart the program. When I restart, the new row is there and everything is as it should be. I have tried revalidating/repainting the panel and frame, I have tried the fire methods. I'm at a loss. Thanks in advance

ActionListener (in adminGUI class) for 'Add' button:

if(source.equals(add2)){
         String c = itb.getText();
         int a = main.getResults();
         boolean matches = Pattern.matches("[A-Z][a-z]+", c);

         if(matches == true){ 
         main.addGenre(a, c); 
       }

String Method(in main class) to add a row to the database table:

public static void addGenre(int a, String b){
    int rowsAdded;
    try {

     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     Connection connect =DriverManager.getConnection("jdbc:odbc:MovieDB");
     Statement stmt = connect.createStatement();
     String query = "INSERT INTO Genres (genre_id, genre_name)" + "VALUES(" + a + ", '" + b + "')";
     rowsAdded = stmt.executeUpdate(query);
    }catch(Exception exc){}
 }

Method(also in main class) to increment the auto-increment-key column:

public static int getResults(){
      int a = 0;
      ResultSet ints = main.getResults("Select genre_id from Genres");
    try {
        while(ints.next()){
            int d = ints.getInt("genre_id");
            if(d>a){
                a = d;    
            }
            a++;
        }  
    } catch (SQLException ex) {
        Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
    }

      return a;
  }

JTable details:

ResultSet rs1 = main.getResults("Select * from Genres"); 
JTable tab1 = new JTable(DbUtils.resultSetToTableModel(rs1));

DbUtils.resultSetToTableModel details :

public class DbUtils {
public static TableModel resultSetToTableModel(ResultSet rs) {
    try {
        ResultSetMetaData metaData = rs.getMetaData();
        int numberOfColumns = metaData.getColumnCount();
        Vector columnNames = new Vector();

        // Get the column names
        for (int column = 0; column < numberOfColumns; column++) {
            columnNames.addElement(metaData.getColumnLabel(column + 1));
        }

        // Get all rows.
        Vector rows = new Vector();

        while (rs.next()) {
            Vector newRow = new Vector();

            for (int i = 1; i <= numberOfColumns; i++) {
                newRow.addElement(rs.getObject(i));
            }

            rows.addElement(newRow);
        }

        return new DefaultTableModel(rows, columnNames);
    } catch (Exception e) {
        e.printStackTrace();

        return null;
    }
}

}

¿Fue útil?

Solución

"I cannot get my JTable to update with a new row unless I restart the program."

I think what you're expecting is that when the database table update, so should your JTable. It doesn't really work like that. You need to update the TableModel, and the JTable will be automatically updated

Since resultSetToTableModel returns a DefuaultTableModel, you can use either of the two methods from DefaultTableModel:

  • public void addRow(Object[] rowData) - Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.

  • public void addRow(Vector rowData) - Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.

So when your are adding the data to the database, you also want to update the DefaultTableModel like this

public static void addGenre(Integer a, String b){
    ...
    rowsAdded = stmt.executeUpdate(query);
    if (rowsAdded > 0) {
        DefaultTableModel model = (DefaultTableModel)tab1.getModel();
        model.addRow( new Object[] { a, b });
    }
}

Also noticed I changed the method signature to Integer instead of int so it will fit with the Object[] passed to addRow. The int you pass to it will get autoboxed to Integer


SIDE NOTES

  • Don't swallow you exception by putting nothing in the catch block. Put something meaningful that will notify you of any exceptions that may occur, like

     catch(Exception ex) {
         ex.printStackTrace();
     }
    
  • You should also close your Connections, Statements, and ResultSets

  • You should use PreparedStatement instead of Statement, to avoid SQL injection.

Otros consejos

private void resetListData() throws ClassNotFoundException, SQLException 
{
    Connection cne = null;
    try {

        Class.forName("org.sqlite.JDBC");
        cne = DriverManager.getConnection("jdbc:sqlite:table.sqlite");
        cne.setAutoCommit(false);
        PreparedStatement psd = (PreparedStatement) cne.prepareStatement("Select * from Genres");                
        psd.execute();
        ResultSet r = psd.getResultSet();
        ResultSetMetaData rsmd = r.getMetaData();
        int count = rsmd.getColumnCount();
        String[] meta = new String[count];
        for (int i = 0; i < count; i++) 
        {
            String name = rsmd.getColumnName(i + 1);
            meta[i] = name;
            //System.out.println(name);
        }
        model = new DefaultTableModel(new Object[][]{}, new String[]{"name", "address"});
        jTable1.setModel(model);
        while (r.next()) 
        {
            Object[] row = new Object[count];
            for (int i = 1; i <= count; ++i) 
            {
                row[i - 1] = r.getString(i);  // Or even rs.getObject() 
            }
            model.addRow(row);
        }
        cne.close();
    } catch (ClassNotFoundException | SQLException e) {
    }
}

Use this code. so you can insert one row at the end of Jtable without restarting application.,

Thanks..

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top