从 ArrayList 创建 JTable [英] Create JTable from ArrayList

查看:40
本文介绍了从 ArrayList 创建 JTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我设法将文件中的对象放入ArrayList,我必须将它们显示到JTable中.

Now that I managed to put the objects from a file into a ArrayList, I have to display them into a JTable.

这些是包含在我的 ArrayList

Lieu<Double, String>(45.573715, -73.900295, "p1");
Lieu<Double, String>(45.573882, -73.899748, "p2");
Lieu<Double, String>(45.574438, -73.900099, "p3");

Lieu 类中,我有方法 getX()getY()

In the Lieu class I have the methods getX() and getY()

但我不知道如何在 JTable 中显示它们.

But I can't figure out how to diplay them in a JTable.

Longitude           Latitude
45.573715           -73.900295
45.573882           -73.899748
45.574438           -73.900099

这是我的开始:

public class MonModel extends AbstractTableModel{

    @Override
    public int getColumnCount() {
        return 2;
    }

    @Override
    public int getRowCount() {
        return l.size();//l is the arraylist that contains the 3 elements
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        if(columnIndex==0){
            return l.get(rowIndex).getX();
        }
        else if(columnIndex==1){
            return l.get(rowIndex).getY();
        }
        return null;
    }

推荐答案

使用 TableModel 来显示 JTable 中的数据.例如:

Use a TableModel for showing data in the JTable. For Example:

在 UI 类中,将表格模型设置为表格.

In UI class, set the table model to the table.

JTable table = new JTable(new MonModel());

表模型类

class MonModel extends AbstractTableModel {

    private List<LatNLon> l;
    private String[] columnNames = {"Longitude", "Latitude"};

    public MonModel() {
        l = new ArrayList<LatNLon>();

        l.add(new LatNLon("45.573715", "-73.900295"));
        l.add(new LatNLon("45.573715", "-73.900295"));
        l.add(new LatNLon("45.573715", "-73.900295"));
    }

    @Override
    public String getColumnName(int column) {
        return columnNames[column];
    }

    public int getColumnCount() {
        return 2;
    }

    public int getRowCount() {
        return l.size();
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        if(columnIndex==0){
            return l.get(rowIndex).getX();
        }
        else if(columnIndex==1){
            return l.get(rowIndex).getY();
        }
        return null;
    }
}

纬度和经度类.

class LatNLon {
    private String x;
    private String y;

    public LatNLon(String x, String y) {
        this.x = x;
        this.y = y;
    }
// Code: For Getters and Setters.
}

另请阅读如何使用表格.

这篇关于从 ArrayList 创建 JTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆