-1
public void populateJTable() {        
    DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
    Object[] rowData = new Object[4];
    TrackService ts = new TrackService();
    ArrayList<Track> tracks = ts.jsonToTracks();

    for (int i = 0; i < tracks.size(); i++) {
        rowData[0] = tracks.get(i).getTrackName();
        rowData[1] = tracks.get(i).getArtist();
        model.addRow(rowData);
    }
    jTable1 = new JTable(model);
}

In my json file I have stored metadata of an mp3 file which stores 5 values. My 'jsonToTracks' method stores them in an ArrayList. I'm trying to get 2 of the values (trackName and artist) from inside my ArrayList and display them in my JTable. My JTable has 4 columns - Name, Artist, Key, Mood. I'm trying to store the trackName and Artist in their corresponding columns. The Key and Mood column should be blank and the Name and Artist fields should be populated. I can't see what I'm doing wrong, can anyone help?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Lewball
  • 1
  • 1
  • 1
  • I have no idea why this was originally closed as a duplicate of: http://stackoverflow.com/questions/4279631/making-arraylist-to-jtable. All that answer does is suggest to use a DefaultTableModel. The OP is using the DefaultTableModel. Anyway, I am reopening the question. – camickr Mar 29 '17 at 15:51

2 Answers2

3

Maybe you should try, moving your rowData initialization inside for loop.

public void populateJTable() {        
    DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
    TrackService ts = new TrackService();
    ArrayList<Track> tracks = ts.jsonToTracks();

    for (int i = 0; i < tracks.size(); i++) {
        Object[] rowData = new Object[4];
        rowData[0] = tracks.get(i).getTrackName();
        rowData[1] = tracks.get(i).getArtist();
        model.addRow(rowData);
    }
    jTable1 = new JTable(model);
}
Dave Ranjan
  • 2,966
  • 24
  • 55
  • Agreed, this may seem a little more logical (and probably a good practice). However, the `DefaultTableModel` actually uses a `Vector` to hold the row data. So the data is copied from the `Array` to a newly created `Vector` when the `addRow()` method is used. So it is ok to reuse the same `Array`. On the other hand I sometimes use a `Vector` with the `addRow()` method. In this case you would need to create the `Vector` from within the loop because the data is NOT copied from the `Vector`. The `Vector` itself is added to the model. A subtle implementation difference between the two methods. – camickr Mar 29 '17 at 16:06
2
jTable1 = new JTable(model);

I suspect the problem is that you are creating a new JTable but you never add the table to the frame.

Instead you should use:

jTable1.setModel( model );

This will replace the data in the existing JTable was I assume you have already added to a JScrollpane that has been added to the frame.

camickr
  • 321,443
  • 19
  • 166
  • 288