Question

Why does the value in my jTable overwrites the first value which are selected from the jcombobox? can somebody help me out with this code:

private void jButton15ActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
    Connection con;
    Statement stmt;
    try {
        // TODO add your handling code here
        Class.forName("sun.jdbc.odbc.JdbcOdbc");
    } catch (ClassNotFoundException ex) {
        JOptionPane.showMessageDialog(null, ex);
    }
    try {
        con= DriverManager.getConnection("Jdbc:Odbc:food");
        stmt= con.createStatement();
        int row = 0;

        String st= JcbSub.getSelectedItem().toString();
        jTable3.setValueAt(st, row, 0);    

            row ++;

        } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, ex);
    } 
}
Was it helpful?

Solution

Although you do increment the row number at the end you've declared it as a local variable which loses its value and gets initialized to 0 at every method call. Hence your first row gets overwritten everytime.

int row = 0; // move this out to a member variable

String st= JcbSub.getSelectedItem().toString();
jTable3.setValueAt(st, row, 0);    

row ++; // this increment currently has no effect on next method call

You're also opening a new database connection every time and not closing it by calling con.close(). In fact, since you're not executing any queries via your Statement object stmt there's no need for all the JDBC code inside the method.

OTHER TIPS

JTable#setValue will only change an existing rows value.

Your should use the TableModel to add new rows. If your using a DefaultTableModel you could use the addRow method

your code is incomplete, i supose because u didnt use anything of the created statement and the row isnt inside any loop to travel inside any data set.

the jtable.setValueAt method needs the value , the index of col, and the index of the row,

setValueAt(Object o, int col, int row)

you are just setting the first row when put the zero at the last parameter jTable3.setValueAt(st, row, 0);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top