How to add data to JTable created in design mode?(如何将数据添加到在设计模式下创建的 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将数据添加到在设计模式下创建的 JTable?
				
        
 
            
        - GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
 - 转换 ldap 日期 2022-01-01
 - 未找到/usr/local/lib 中的库 2022-01-01
 - Eclipse 的最佳 XML 编辑器 2022-01-01
 - 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
 - java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
 - 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
 - 如何指定 CORS 的响应标头? 2022-01-01
 - 获取数字的最后一位 2022-01-01
 - 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
 
						
						
						
						
						
				
				
				
				