从mySQL数据填充Jtable

时间:2012-12-26 06:04:48

标签: java swing user-interface jtable tablemodel

我不知道如何以及在何处启动我的代码。我尝试在Google中搜索如何使用java代码在netbeans GUI中填充Jtable。实际上,我不希望我的MySql数据库中的所有列都将被显示。所以我创建了表模型。我不知道这是否有效。但事情是我不知道接下来要做的事情。我希望它显示在我的Jtable中,名为" tblList"。请帮帮我怎么样。这是我的" ListOfMembersModel"

  import java.text.DateFormat;
  import java.util.ArrayList;
  import java.util.Locale;
  import javax.swing.table.DefaultTableModel;
  import rtu.tomis.bom.Member;

  public class ListOfMembersModel extends DefaultTableModel{
private ArrayList<Member> members;


public ArrayList<Member> getMembers() {
    return members;
}

public void setMembers(ArrayList<Member> members) {
    this.members = members;
}


public ListOfMembersModel(ArrayList<Member> members){
    this.members = members;
    String[] columns = {"MemberId", "Voters ID", "Full Name",  "Age",  "Address", "Gender", "Birthday", "Contact Number", "Email Address", "Type of Membership"};
    this.setColumnIdentifiers(columns);
}

 public int getRowCount() {
    int rows = 0;
    if(this.members!=null && this.members.size()>0){
        rows = this.members.size();
    }
    return rows;
}

public int getColumnCount() {
    int columns = 10;
    return columns;
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {

    String s = "";
    Member member = null;
    if(this.members!=null && this.members.size()>0){

        member = (Member)this.members.get(rowIndex);

        switch(columnIndex){
            case 0:
                s = ""+member.getMemberId();
                break;
            case 1:
                s = member.getVotersId();
                break;
            case 2:
                s = member.getFullname();
                break;
            case 3:
                s = "" + member.getAge();
                break;
            case 4:
                s = member.getFulladdress();
                break;
            case 5:
                s = member.getGender();
                break;
            case 6:
                DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US);
                String bday = df.format(member.getBirthday());
                s = ""+bday;
                break;

               case 7:
                s = "" + member.getContactNo();
                break;

                case 8:
                s = member.getEmailAddress();
                break;

                 case 9:
                s = member.getMembershipType();
                break;

        }
    }
    return s;
}

public boolean isCellEditable(int row, int col){
    return false;
}

你能帮我解决一下如何填充我的Jtable。谢谢。

1 个答案:

答案 0 :(得分:1)

答案似乎是

jTable.setModel(new ListOfMembersModel(members));

某些更改可能必须向表侦听器发出通知,其中一个是JTable,请参阅AbstractTableModel.fire...方法