How can i display the database data to an JTable(dynamic) in Swings?
We are using hibernate
in business layer,but the task is,
by using the JTable
in Swing
to display the dynamic data(Swing
) from the database.
code:
Criteria criteria=session.createCriteria(User.class);
//here user.class is pojo class in hibernate.
List studentlist= criteria.list();
System.out.println("records开发者_如何学运维"+studentlist);
//here the data is showing in hibernate console, but how to represent that data in the format of "jtable".
We can retrieve a List of Objects from hibernate. To show the Objects in JTable, just inherited a class from AbstractTableModel and supply getRowCount() ,getColumnCount() and getValueAt() methods. And the getColumnName method is often need to be overrided to show the column name you want, not the X,Y,Z form. Lets say You have a PERSON table in some database and its corresponding persistent class Person.
Source of PersonTableModel.java:
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
import javax.swing.table.AbstractTableModel;
public class PersonTableModel extends AbstractTableModel
{
private static final long serialVersionUID = 6105842825518764825L;
private ArrayList<Person> PersonList;
public PersonTableModel()
{
super();
SessionFactory sf=new Configuration().configure().buildSessionFactory();
Session session=sf.openSession();
Query q=session.createQuery("from Person");
PersonList=new ArrayList<Person>(q.list());
session.close();
sf.close();
}
public int getRowCount()
{
return PersonList.size();
}
public int getColumnCount()
{
return 5;
}
public Object getValueAt(int rowIndex, int columnIndex)
{
Person p=PersonList.get(rowIndex);
Object[] values=new Object[]{p.getId(),p.getFirstname(),p.getLastname(),
p.getAge(),p.getDescription()};
return values[columnIndex];
}
@Override
public String getColumnName(int column)
{
String[] columnNames=new String[]{"id","FirstName","LastName","Age","description"};
return columnNames[column];
}
}
Then create a PersonTableModel Object and set the JTable’s model to it
I recommend you read the tutorial How to use tables, from Java.
If you have a more specific need, edit your question to add details.
I've never used hibernate, but based on the code provided it looks like the data from your database is returned in a List. Therefore you will need to create a custom TableModel to access the data in the List.
The BeanTableModel might help you out.
精彩评论