how to add items to a JTable using a loop

前端 未结 2 1111
不思量自难忘°
不思量自难忘° 2021-01-28 08:09

I came up with this loop here:

    for(int i = 0; i < memberArrayList.size(); i++){
        int j = 0;
        memberTable.setValueAt(memberArrayList.get(i).g         


        
相关标签:
2条回答
  • 2021-01-28 08:45

    The answer will depend on what type of TableModel you are using, for example, if you are using a DefaultTableModel you could use something like...

    DefaultTableModel memberTable= ...;
    
    for(int i = 0; i < memberArrayList.size(); i++){
        Object[] rowData = new Object[]{
            memberArrayList.get(i).getFirstName(),
            memberArrayList.get(i).getLastName(), 
            memberArrayList.get(i).getEmail(), 
            memberArrayList.get(i).getPhoneNumber(),
            memberArrayList.get(i).getLevel()
            };
        memberTable.addRow(rowData);
    }
    

    This assumes that you only want to add rows to the end of the table model ;)

    Personally, I'd prefer to add each member to the table model as a single entity, but that's just me

    Take a look at How to Use Tables for more details...

    0 讨论(0)
  • 2021-01-28 08:52

    Swing components are using MVC pattern. JTable is the view, TableModels are the model that contains data.

    you can subclass AbstractTableModel to achieve your goal.

    public class MyTableModel extends AbstractTableModel {
        // override these methods:
        // getColumnCount, getRowCount, getValueAt
        // and add data manipulation methods
    }
    

    then your table is created using MyTableModel

    MyTableModel mtm = new MyTableModel(......);
    JTable table = new JTable(mtm);
    

    then call data manipulation methods in mtm. something like

    mtm.addPerson(new Person(......));
    
    0 讨论(0)
提交回复
热议问题