如何将数据添加到在设计模式下创建的 JTable? [英] How to add data to JTable created in design mode?

查看:27
本文介绍了如何将数据添加到在设计模式下创建的 JTable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个初始的 JFrame,其中包含一个三列的表,如下所示:

I created an initial JFrame that contains a table with three columns, as shown below:

这个 JFrame 是在设计模式下创建的,所以现在在面板的构造函数中,我想加载一些数据,这样当用户选择打开这个 JFrame 时,数据就会被加载.

This JFrame was created in design mode, and so now in the panel's constructor, I want to load some data so when the user selects to open this JFrame, the data is loaded.

我的列数据类型是对象(通常状态"用于表示共享状态的图像 - 活动或非活动),字符串表示共享名称,整数表示连接到该共享的活动客户端数量.

My column data types are Object (generally 'Status' is for an image representing the status of the share - active or inactive), String for the share's name and integer for the number of active clients connected to that share.

我的问题是,如何通过代码向 JTable 添加行?

My question is, how to I add rows to a JTable via code?

推荐答案

以简化的方式(可以改进):

In a simplified way (can be improved):

class MyModel extends AbstractTableModel{

    private ArrayList<Register> list = new ArrayList<Register>();

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

    @Override
    public int getRowCount() {
        return list.size();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Register r = list.get(rowIndex);
        switch (columnIndex) {
        case 0: return r.status; 
        case 1: return r.name;
        case 2: return r.clients; 
        }
            return null;
    }

    public void addRegister(String status, String name, String clients){
        list.add(new Register(status, name, clients));
        this.fireTableDataChanged();
    }

    class Register{
        String status;
        String name;
        String clients;

        public Register(String status, String name, String clients) {
            this.status = status;
            this.name = name;
            this.clients = clients;
        }
    }

}

然后,在面板的构造函数中:

Then, in the panel's constructor:

MyTableModel mtm = new MyTableModel();
yourtable.setModel(mtm);

添加一行:

mtm.addRegister("the status","the name","the client(s)");

更改列的标题名称:

TableColumn statusColumn = yourtable.getColumnModel().getColumn(0); 
statusColumn.setHeaderValue("Status");

这篇关于如何将数据添加到在设计模式下创建的 JTable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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