Swing/JTable Not Updating After Bound Data Fires Change

前端 未结 4 1742
悲哀的现实
悲哀的现实 2021-01-22 18:16

I have a JTable which is bound to my EventTracker bean, essentially a wrapper around a list which I will use as append/clear only (i.e., a simple log). Problem is, when I add en

相关标签:
4条回答
  • 2021-01-22 18:32

    It's not clear how you are binding the the EventTracker class to the table.I'm assuming you are using a corresponding editor and renderer class and then setting the render and editor like this table.setDefaultRenderer(EventTracker.class,new EventTrackerRender()); and table.setDefaultEditor(EventTracker.class,new EventTrackerEditor());.Editor is used in case only if you need to change the EventTracker bean through the table.

    If it done from outside the table (ie.through code) override the setValueAt function in the Table model and then get the EventTracker Object(which is the current object) using getValueAt and make necessary changes (if Eventtracker is mutable object).In case of immutable object make a new object of EventTracker and set it to the object array.After this you should either call fireTableDataChanged() which is going to repaint the whole table or call fireTableCellUpdated(row,col) for a particular cell to be rendered again.

    0 讨论(0)
  • you need to tell the table that the datamodel changed:

    .fireTableDataChanged()

    is the correct method; assuming that your table descends from the Abstract Table Model.

    (so yes, I agree with trashgod)

    0 讨论(0)
  • 2021-01-22 18:44

    Assuming your data model derives from AbstractTableModel, you can update your model explicitly and fire the appropriate update method implemented in the abstract parent. Moreover, updates must occur on the EDT, typically using invokeLater(). See also Listening for Data Changes and Firing Data Change Events.

    EventQueue.invokeLater(new Runnable() {
    
        @Override
        public void run() {
            // update model, which should fire the appropriate event
        }
    });
    
    0 讨论(0)
  • 2021-01-22 18:51

    I was really intent on getting the data binding working. The answers recommended were good reading, but would have led me to writing a lot of code. I didn't want to handle giving the row count/column count logic and all that extra work. As a result, this solution may provide less control but it's pretty quick and easy for this read-only workflow.

    The document at http://swinglabs.org/docs/presentations/2007/DesktopMatters/beans-binding-talk.pdf gave me the skinny. The trick was to use ObservableCollection / ObservableList(new ArrayList<Event>) as the datastore. Whenever I add another entry it is automatically reflected in the JTable.

    Great!

    0 讨论(0)
提交回复
热议问题