• Post Reply Bookmark Topic Watch Topic
  • New Topic

fireTableRowsInserted()

 
mohamed hamdy
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
i was testing adding rows dynimacally to a JTable.
i was thinking that i can use i method for inserting in a class derived from AbstractTableModel such as setValueAT (by overriding it) or any onother custom method that i call by the object of the table model and when i finish i use fireTableRowsInserted to update the table with the new rows so i wrote the following code and then i intended to try it with commenting calling fireTableRowsChanged then i found that it display the first ten rows (the generating thread inserts ten rows then waits until another thread notify him) then it stops.
i would like yo know wheather it's a threads problem or i misunderstood the real need of fireTableRowsInserted.
look at the code:
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.util.*;
public class TableTest extends JFrame{
private MyTableModel tableModel;
private boolean runnerStopped;
private int firstRow,lastRow=9;
TableTest(){
super("table");
Container contentPane=getContentPane();
tableModel=new MyTableModel();
JTable table=new JTable(tableModel);
JScrollPane jScrollPane=new JScrollPane(table);
contentPane.add(jScrollPane);
new Runner().start();
new Manager().start();
}
synchronized void updateTable(){
if(runnerStopped){
//i commented the following line in the second trial
tableModel.fireTableRowsInserted(firstRow,lastRow);
firstRow+=10;
lastRow+=10;
runnerStopped=false;
notify();
}
else{
runnerStopped=true;
try{
wait();
}
catch(InterruptedException e){
}
}
}
class Runner extends Thread{
private int row,column;
public void run(){
while(true){
Random rnd=new Random();
byte[] bytes=new byte[10];
rnd.nextBytes(bytes);
String datum=new String(bytes);
tableModel.setValueAt(datum,row,column++);
if(column==10){
column=0;
row++;
}
if((row%10==1)&(column==0)){
updateTable();
try{
sleep(10000);
}
catch(InterruptedException e){
}
}
}
}
}
class Manager extends Thread{
public void run(){
while(true){
if(runnerStopped){
updateTable();
}
}
}
}
public static void main(String[] args){
TableTest table=new TableTest();
table.setSize(600,600);
table.setVisible(true);
}

}
class MyTableModel extends AbstractTableModel{
private ArrayList data;
MyTableModel(){
data=new ArrayList();
}
public int getRowCount(){return data.size();}
public int getColumnCount(){return 10;}
public Object getValueAt(int row,int column){
String[] arr=(String[])data.get(row);
return arr[column];
}
public void setValueAt(Object value,int row,int column){
String[] arr;
if(column==0){
arr=new String[10];
}
else{
arr=(String[])data.get(row);
}
arr[column]=(String)value;
data.add(row,arr);
}
public String getColumnName(int column){
return "column"+(column+1);
}
}
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!