如何用Java中的对象属性填充JTable?

时间:2018-06-26 13:25:53

标签: java user-interface object jtable

说我有一个“狗”类来创建狗对象。看起来像这样:

public class Dog {
private String name;
private String colour;
private String size;
private int age;

public Dog(String name, String colour, String size, int age){
    this.name = name;
    this.colour = colour;
    this.size = size;
    this.age = age;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getColour() {
    return colour;
}

public void setColour(String colour) {
    this.colour = colour;
}

public String getSize() {
    return size;
}

public void setSize(String size) {
    this.size = size;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
  }
}

说现在我已经在ArrayList中创建并存储了10个狗对象。如何使用JTable以列名,名称,颜色,大小等显示这些内容?

1 个答案:

答案 0 :(得分:0)

您可以像下面那样填充jtable:

public void initTable(ArrayList<Dog> dogList, JTable table) {

  DefaultTableModel model = (DefaultTableModel)table.getModel();
     for(Dog dog : dogList){
          model.addRow(new Object[]{dog.getName(), dog.getColor(), dog.getAge(), ... });
     }
     table.setModel(model);
}

您可以像下面那样实现您的表模型:

new javax.swing.table.DefaultTableModel (
    new String [] {
        "Name","Color", "Age", ...
    },0
) {
    Class[] types = new Class[]{
        java.lang.String.class,
        java.lang.String.class,
        java.lang.Integer.class, 
        ...
    };
}