1

I'm populating data from my database into my JTable. After I add new data and press Refresh button, I want to remove the existing row displayed on table before retrieving the new data. How can I remove the existing row?

Here is the original table with data [a,1].

Original

This is the table after I add new data [b,1] and press refresh button. The original data [a,1] is still shown in the table:

After insert

JButton refreshButton = new JButton("Refresh");
refreshButton.setBounds(188, 248, 101, 23);
panel.add(refreshButton);

refreshButton.addActionListener(new ActionListener() 
{                        
    public void actionPerformed(ActionEvent ae)
    {

    DefaultTableModel model = new DefaultTableModel(data,columnNames);
    int rowCount = model.getRowCount(); 

    for (int x = 0; x <=rowCount; x++)
    {
        model.removeRow(x);
    }


        try
        {                       
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/watchlist","root","root");

            String sql = "SELECT * FROM watchlist";
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData md = rs.getMetaData();    


            int columns = md.getColumnCount();  

            while (rs.next())
            {   
                Vector row = new Vector(columns);

                for (int i=1; i <= columns; i++)
                {
                    row.addElement( rs.getObject(i) );              
                    System.out.println( rs.getObject(i).toString());        
                }                           

                data.addElement(row);   

                table.revalidate(); 
                table.repaint();
                panel.repaint();

            } // end while  

        } // end try

        catch (Exception e){
        }
    }

});
Lily S
  • 245
  • 1
  • 8
  • 18

4 Answers4

2

I think that I saw this question,

1) search for ResultsetTableModel / TableFromDatabase (better)

  • (if Database Connection (so hard and lazy action) isn't closed during Applications lifecycle)

a) replace JTable contents

b) works with embeded Db of database placed in intranet immediatelly

  • dis

all processes is durring EDT, then GUI waiting for SQL statement

for most code examples required to move Xxx.close to the finally block

2) most complex workaround you have to use SwingWorker, better and easiest way is to load data from Runnable#Thread

3) you can remove row(s) from TableModel,

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • Thanks mKorblel. I'm using the 3rd option of removing rows, it's working fine. – Lily S May 14 '12 at 12:36
  • glad to help you, but you choosed wrong option I still this that you have to use [Table From Database](http://tips4java.wordpress.com/2009/03/12/table-from-database/) instead – mKorbel May 14 '12 at 12:46
1

You can either remove the row (see DefaultTableModel.removeRow) or put the new data into a new table model, and replace the table's table model with JTable.setModel()

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67
  • I'm able to remove one row with model.removeRow(0); .. How can I delete all the available rows? – Lily S May 14 '12 at 12:01
1

Upon refreshing button, call the following:

DefaultTableModel model = new DefaultTableModel(data,col);
model.removeRow(1); // first row in this case

In this case you need to manage to get the data , columns and the row count.Data is your actual data, col is the number of columns.

UVM
  • 9,776
  • 6
  • 41
  • 66
  • Thanks for the reply! it helped me remove the first row of data. What if I have more than 1 data available? I've added a loop to retrieve the rowCount of the table. But it doesn't work. – Lily S May 14 '12 at 11:56
  • @LilyT, you need to get the rowCount then insde a for loop, call model.removeRow(i); – UVM May 14 '12 at 12:00
  • i already inserted a loop with the model.removeRow inside (i've added it in the code above). i've got this error: Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2 >= 1 – Lily S May 14 '12 at 12:05
  • @LilyT, which means that index is more than the table row count.paste the code here. – UVM May 14 '12 at 12:09
  • DefaultTableModel model = new DefaultTableModel(data,columnNames); int rowCount = model.getRowCount(); for (int x = 0; x <=rowCount; x++) { model.removeRow(x); } – Lily S May 14 '12 at 12:12
  • @LilyT, the for loop should be for (int x = 0; x – UVM May 14 '12 at 12:13
  • i still get this error: Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2 >= 1 – Lily S May 14 '12 at 12:18
  • the link posted by mKorbel seemed similar. can you check it out? http://stackoverflow.com/a/10414459/714968 – Lily S May 14 '12 at 12:29
  • The solution from the link works! Thanks for your guidance UNNI :) – Lily S May 14 '12 at 12:34
  • Just to have the answers all in one place in case someone comes looking... * The correct answer is DefaultTableModel.setRowCount(0) * The problem with the loop discussed above is the usual noob attempt to remove everything from a list, one at a time - you either have to start with the last item, and count down, or remove item zero as many times as you have items. Otherwise, you wind up referencing item indexes that no longer exist (hence the Exception) So, either: for(int i = rowCount -1; i >= 0; --i) { model.removeRow(i); } or for(int i = 0; i < rowCount; i++) { model.removeRow(0); } – GreyBeardedGeek May 16 '12 at 11:31
-2

enter image description here

this method i used to populte data in any jTbale

it clear jtable (refresh ) jtable befor populte new data

this line cleare jatble befor populate data

mytable.setModel(new DefaultTableModel(null, colname));

public static void FilltableV(JTable mytable, String sql){ Connection con = null;

    Statement Cmd = null;
    ResultSet rs = null;
try {


    con = DriverManager.getConnection("jdbc:mysql://localhost/alserg", "root", "");

    sql="SELECT * FROM products";
    Cmd=con.createStatement();
    rs=Cmd.executeQuery(sql);
    ResultSetMetaData rsmt=rs.getMetaData();
    int colno =rsmt.getColumnCount();
    Vector colname =new Vector();
    DefaultTableModel mytab =new  DefaultTableModel();
    Vector rows =new Vector();
    for(int i=1 ;i< colno;++i){
        colname.addElement(rsmt.getColumnName(i));
        mytab.setColumnIdentifiers(colname);

    }

    while (rs.next()){
        rows= new Vector();
        for (int j=1;j<colno;++j){
            rows.addElement(rs.getString(j));


        }
        mytab.addRow(rows);
        mytable.setModel(new DefaultTableModel(null, colname));
        mytable.setModel(mytab);



    }
} catch (SQLException ex) {
    Logger.getLogger(products.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
    try {
        rs.close();
        Cmd.close();
        con.close();
    } catch (SQLException ex) {
        Logger.getLogger(AlseragLang.class.getName()).log(Level.SEVERE, null, ex);
    }


}

}

  • The basic idea here is OK. You can use `table.setModel()` to apply a new set of data. But the code is not very clear. – Enwired Nov 11 '16 at 20:50
  • i want to refere to how to refresh jtable in simple way and i made this method to show how to refresh jtable and you use it with any jtable – user7147618 Nov 11 '16 at 22:21
  • the fist line of code out of code area public static void FilltableV(JTable mytable, String sql){ Connection con = null; this method dos'nt nead more than to par jtable name, sql query and i focus on clear jtable by setmodel it self and by add one line mytable.setModel(new DefaultTableModel(null, colname)); – user7147618 Nov 11 '16 at 22:27
  • to claer rows before populte new data by next line – user7147618 Nov 11 '16 at 22:28