在我这个例子中,我主要说明的一点是:在jtable中,有时需要让新添加的数据出现在表格的第一行。
这一点的应用主要在客户端的告警信息显示时需要。
为了方便大家,我总结出一个简单的例子供大家参考:
注意:我的实体类是用hibernate与数据库表映射的,在这里,我没有列出hibernate的具体操作,如果有需要的,请和我探讨。
我定义一个学生实体类:
public class student {
private int id;
private String name;
private int score;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
jtable测试实现类:
import hibernate.hibernateUtil;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import org.hibernate.Query;
public class testframe extends JFrame {
JTable jtable;
JScrollPane jsp;
private student stu = new student();
private LinkedList ll = new LinkedList();//用linkedlist对象实现栈操作
DefaultTableModel dtm;
public testframe(){
init();
}
public void init(){
String [] coltitle = {"编号","姓名","成绩"};
dtm = new DefaultTableModel(coltitle, 0); // 定义一个表的模板
jtable.setModel(dtm);
jsp.getViewport().setView(jtable);
inittable();//初始化表格数据
}
public void inittable(){
org.hibernate.classic.Session
sess = hibernateUtil.getSessionFactory().openSession();
sess.beginTransaction(); //用hibernate对数据表操作,实现面向对象功能
String hql = "FROM Users
";
Query query =
sess.createQuery(hql);
List list =
query.list();
Iterator iteator =
list.iterator();
while (iteator.hasNext())
{
stu =
iteator.next();
ll.addFirst(stu);//把对象推入栈中
}
for(int
i=0;i<=ll.size();i++){
stu =
(student) ll.removeFirst();//把对象推出栈,目的是让新添加的学生出现在jtable的第一行
String stuid
= stu.getId().toString();
String
stuname = stu.getName();
String
stuscore = stu.getScore().toString();
String []
cols = {stuid,stuname,stuscore};
dtm.addRow(cols);
jtable.invalidate();
}
}
public static void main(String[] args) {
// TODO Auto-generated method
stub
testframe tf = new
testframe();
tf.setSize(400,400);
tf.setVisible(true);
tf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
-----------------------------------------OVER----------------------------------------------------