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?
基础教程推荐
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
