Win a copy of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications this week in the Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Keep JTable selection when adding a row  RSS feed

 
Ralph Cook
Ranch Hand
Posts: 479
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a real-time application that adds rows to the model supporting a JTable from time to time. Every time a row is added, any user row selection is lost.

I am looking for a technique to use so that, if there is a row selected when a row is added, it remains selected after (and preferably while) a row is added.

Ideallly this will be something I can do in GUI-related classes; the part of the current code that adds a row does not have a reference to the JTable display; the former is model, the latter is view. There is currently no reference to the JTable in the code that adds a row to the model, I'm hoping I don't have to put one there to grab the selected row, add the new row, and then select the selected row again; that would seriously mix UI and modelling logic.

rc

 
Rob Camick
Ranch Foreman
Posts: 2818
15
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Adding a row does not change the selection model.

You must be invoking the wrong fireXXX event. you should be using fireTableRowsInserted(...).
 
Martin Vajsar
Sheriff
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ralph Cook wrote:I am looking for a technique to use so that, if there is a row selected when a row is added, it remains selected after (and preferably while) a row is added.

Rob is right. But in addition, the "preferably while" part is suspicious. Do you update the model from a background (non-GUI) thread? If so, you must properly synchronize. Otherwise, if the table gets repainted while your model is being updated, it could provide inconsistent data to JTable.

I was trying to implement background updates some time ago but then gave up. I now update models always from the GUI thread. In this case no change in the GUI will be displayed while model is updated, including changes in the table selection (row addition does not change selection, but eg. row deletion clearly can).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!