Search code examples
javaarraylistjtabledefaulttablemodel

Loading Data from ArrayList Unto a DefaultTableModel


Please I am trying to load data stored in an ArrayList unto a DefaultTableModel but I dont see the data coming up. please review my code below.

// this is to save to the array.
    ArrayList<MusicEdit> musiclist = new  ArrayList<MusicEdit>();
    code = Integer.parseInt(txtAddMusicCode.getText());
    title = txtAddMusicTitle.getText();
    artist = txtAddMusicArtist.getText();
    price = Integer.parseInt(txtAddMusicprice.getText());
    MusicEdit s = new MusicEdit(code, title, artist, price);
    musiclist.add(s);
    JOptionPane.showMessageDialog(null, "Added Successfully");

And to load the table Model, this what I've got.

public class DisplayMusicCD extends javax.swing.JFrame {
    // Here is to load the TableModel
    String[] columnName = {"Code", "Title", "Artist", "Price"};
    DefaultTableModel dtm = new DefaultTableModel(columnName, 0);
    ArrayList<MusicEdit> musiclist= new  ArrayList<MusicEdit>();     

public void loadAll(){

    for (Object s : musiclist) {
       dtm.addRow( (Object[]) s);
    }

    tblMusic.setModel(dtm);
}

public DisplayMusicCD() {      

    initComponents();
    loadAll();
}

Please what I'm I missing here, the Table loads but only the column names shows up but the data doesn't show up. I tried using AbstractTableModel but I did not no my way around it. so its not an option presently. Thanks in advance.


Solution

  •     public class MusicEdit {
    
        public ArrayList<MusicEdit> getMusiclist() {
            ArrayList<MusicEdit> musiclist = new ArrayList<MusicEdit>();
            code = Integer.parseInt(txtAddMusicCode.getText());
            title = txtAddMusicTitle.getText();
            artist = txtAddMusicArtist.getText();
            price = Integer.parseInt(txtAddMusicprice.getText());
            MusicEdit s = new MusicEdit(code, title, artist, price);
            musiclist.add(s);
                return musiclist;
            }
    
        }
    
    
        public class DisplayMusicCD extends javax.swing.JFrame {
        // Here is to load the TableModel
        String[] columnName = {"Code", "Title", "Artist", "Price"};
        MusicEdit musicEdit =  new MusicEdit ();
    
        DefaultTableModel dtm = new DefaultTableModel(columnName, 0);
        ArrayList<MusicEdit> musiclist = musicEdit.getMusiclist();    
    
        public void loadAll(){
        for (Object s : musiclist) {
           dtm.addRow( (Object[]) s);
        }
    
        tblMusic.setModel(dtm);
    }
    
        public DisplayMusicCD() {   
    
    
    
        initComponents();
        loadAll();
    }
    

    I code it here, to give you and idea how to do it. Give it a try i should work for you.