import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.table.AbstractTableModel;
/**
*构造函数
*/
public class TableValues extends AbstractTableModel{
private static final long serialVersionUID = 1L;
public String[] columnNames;
public Object[][] values ;
public TableValues(String[] columnNames,List<Map<String,Object>> vs){
this.columnNames=columnNames;
values=listToArr(vs,columnNames.length);
}
public int getColumnCount() {
return values[0].length;
}
public int getRowCount() {
return values.length;
}
public Object getValueAt(int rowIndex, int columnIndex) {
return values[rowIndex][columnIndex];
}
/**
* 获取列名
*/
public String getColumnName(int column){
return columnNames[column];
}
/**
* list<map> 转变成二位数组
* [@param](https://my.oschina.net/u/2303379) list
* [@param](https://my.oschina.net/u/2303379) titleLength
* [@return](https://my.oschina.net/u/556800)
*/
private static <T> Object[][] listToArr(List<Map<String,Object>> list,int titleLength){
Object[][] data=new Object[list.size()][titleLength];
for(int i=0;i<list.size();i++){
Map<String,Object> map = list.get(i);
Set<Map.Entry<String,Object>> set=map.entrySet();
int index=titleLength-1;
for(Map.Entry<String,Object> entry:set){
if(index <titleLength){
data[i][index]=entry.getValue();
}
index=index-1;
}
}
return data;
}
}
================================================================
import java.awt.BorderLayout;
import java.awt.Container;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class SimpleTableTest extends JFrame{
private static final long serialVersionUID = -4172876583187222326L;
protected JTable table;
public SimpleTableTest(){
Container pane = getContentPane();
pane.setLayout(new BorderLayout());
List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
Map<String,Object> map=new HashMap<String,Object>();
map.put("name", "何素华");
map.put("sex", "女");
map.put("age", "27");
Map<String,Object> map2=new HashMap<String,Object>();
map2.put("name", "徐良俊");
map2.put("sex", "男");
map2.put("age", "28");
list.add(map);
list.add(map2);
TableValues tv = new TableValues(new String[]{"姓名","性别","年龄"},list);
table= new JTable(tv);
// table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//设置行高
table.setRowHeight(30);
//必须把table放入JScrollPane才会有列名出现
JScrollPane jsp = new JScrollPane(table);
pane.add(jsp,BorderLayout.CENTER);
}
public static void main(String[] args) {
SimpleTableTest stt = new SimpleTableTest();
stt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
stt.setSize(400,200);
stt.setVisible(true);
}
}
转载于:https://my.oschina.net/v512345/blog/830175
今天的文章【Swing系列】JTable 与 AbstractTableModel分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/31190.html