Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JTable and JScrollPane problem

 
Andrew Cubides
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a JScrollPane containing a JTable.... I have an "Add New Row" button that creates a new blank row in the JTable... my problem is that the scrollpane doesn't seem to update when the table keeps growing due to added rows. I can keep adding rows but then they disappear below the scrollpane and I can't scroll down to see them.
Here is the code from the action listener of the "Add New Row" button:
-------------------------
Vector v = new Vector();
DefaultTableModel dfm = (DefaultTableModel)table.getModel();
dfm.addRow(v);
int rowCount = table.getRowCount();
dfm.fireTableStructureChanged();
table.setModel(dfm);
table.revalidate();
pane.doLayout();
-------------
As you can see I tried every method I could think of to try and get the ScrollPane to update.
Any insight would be great, thank you...
Andrew
 
SAFROLE YUTANI
Ranch Hand
Posts: 257
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What on earth are you doing? First of all, you need to understand Swing's Model/Delegate framework. When the data model of the table is changed, the table view is automatically updated. You are not responsible to update the layouts, fire events, or clean the kitchen sink.
You should initialize your table, table model and scroll pane like this...
DefaultTableModel dtm = new DefaultTableModel();
JTable t = new JTable( dtm);
JScrollPane sp = new JScrollPane( t);
//then add the scroll pane to your panel and you're ready to go!
After this code, you can literally forget about the table itself provided that you keep reference to the table model because all of your updates should occur through the model and not through the table itself. You can add rows, delete them, remove all rows, anything you want, and the table view will be updated for you.
Hope it helps
SAF
 
San Su
Ranch Hand
Posts: 313
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Andrew Cubides,
What you are doing is correct except the following unnecessary lines
dfm.fireTableStructureChanged();
table.setModel(dfm);
table.revalidate();
pane.doLayout();
You dont need those. You dont need to set the table model each and every time when you add a row in your table.
Ok Let's come to the problem, I am pretty sure that you should
be getting "ArrayIndexOutOfBoundsException"( i am using JDK1.2.2). I dont know whether it's a bug or not. Set the
size of your vector equals to the column count. That will
solve your problem. If not, let me know..

[This message has been edited by Sankar Subbiah (edited July 10, 2001).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic