Dear friends i would like to know how to display the result set to jtable using rs2xml i know jtablename.setmodel(dbutils.setresultsettotable(rs)); but i would like to know that how to retriev all records and show them in jtablle my code is
private void search_by_topic() throws SQLException, ClassNotFoundException {
try
{
SessionFactory sf;
Configuration cfg=new Configuration();
System.out.println("search_by_topic me agaya");
cfg.configure("hiber_config/hibernate.cfg.xml");
sf=cfg.buildSessionFactory();
Session ses=sf.openSession();
ses.beginTransaction();
Query qr1=ses.createQuery("from Topic where chapter_id=:chapter_id");
qr1.setParameter("chapter_id", chap_id);
List<Topic> topic_list=qr1.list();
top_id=topic_list.get(jComboBox3.getSelectedIndex()).getTopic_id();
System.out.println("Topic ID is "+top_id);
Query qr2=ses.createQuery("from Test as t where t.import_level=:import_level and t.import_level_id=:import_level_id");
qr2.setParameter("import_level", topicimport);
qr2.setInteger("import_level_id",top_id);
List<Test> test_list=qr2.list();
//Field[] fields = null;
System.out.println("Size of test_list is"+test_list.size());
//Iterator<Test> itr=test_list.iterator();
int[] test_id=new int[test_list.size()];
for(int j=0;j<test_list.size();j++)
{
System.out.println("Test_List Import Wale me agaya");
//fields=t.getClass().getDeclaredFields();
test_id[j]=test_list.get(j).getId();
System.out.println("test_id: is "+test_id[j]);
}
System.out.println("Size of test_id array is "+test_id.length);
for(int j=0;j<test_id.length;j++)
{
System.out.println("test_id now is "+j);
int studentid=98;
String sqlquery="SELECT ST.ID id,ST.STUDENT_ID student_id,ST.attemptNumber attempt_Number,ST.TEST_ID testId,ST.TEST_ID student_test_id,T.description description,T.test_duration test_duration,T.test_score Test_Score,ST.SCHEDULED_START_TIME_BEGIN scheduled_start_time_begin,ST.SCHEDULED_START_TIME_END scheduled_start_time_end,ST.TEST_START_DATE test_start_date,ST.LAST_ACTIVE_TIME test_last_active_time,ST.TEST_ATTEMPTED test_attempted,ST.ALLOW_VIEW_REPORT allow_view_report FROM student_test as ST,test as T WHERE ST.PAYMENT_STATUS='A' AND ST.TEST_ID = T.id AND ST.STUDENT_ID='"+studentid+"' AND ST.TEST_ATTEMPTED='0' AND T.id='"+test_id[j]+"' ORDER BY ST.ID";
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/school_db","root","");
Statement pst=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs=pst.executeQuery(sqlquery);
System.out.println(rs.getRow());
System.out.println(rs.toString());
jTable1.revalidate();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
//jTable1.revalidate();
/*SessionFactory sf1;
Configuration cfg1=new Configuration();
System.out.println("join query me agaya");
cfg1.configure("hiber_config/hibernate.cfg.xml");
sf1=cfg.buildSessionFactory();
Session ses1=sf1.openSession();
ses1.beginTransaction();
ses1.doWork(new Work()
{
#Override
public void execute(java.sql.Connection cnctn) throws SQLException
{
java.sql.PreparedStatement pst=cnctn.prepareStatement(sqlquery);
rs=pst.executeQuery();
System.out.println(rs.toString());
}
});
ses1.getTransaction().commit();
}
ses.getTransaction().commit();
System.out.println("Test Data Retrieved");
ses.close();*/
}
}
catch(HibernateException e)
{
e.printStackTrace();
}
}
}
my code is working here correctly and i am able to retrieve all the resultset but in jtable i am only getting the last loop record not every loop record
Please help me
private void search_by_topic() throws SQLException, ClassNotFoundException {
try
{
SessionFactory sf;
Configuration cfg=new Configuration();
System.out.println("search_by_topic me agaya");
cfg.configure("hiber_config/hibernate.cfg.xml");
sf=cfg.buildSessionFactory();
Session ses=sf.openSession();
ses.beginTransaction();
Query qr1=ses.createQuery("from Topic where chapter_id=:chapter_id");
qr1.setParameter("chapter_id", chap_id);
List<Topic> topic_list=qr1.list();
top_id=topic_list.get(jComboBox3.getSelectedIndex()).getTopic_id();
System.out.println("Topic ID is "+top_id);
Query qr2=ses.createQuery("from Test as t where t.import_level=:import_level and t.import_level_id=:import_level_id");
qr2.setParameter("import_level", topicimport);
qr2.setInteger("import_level_id",top_id);
List<Test> test_list=qr2.list();
//Field[] fields = null;
System.out.println("Size of test_list is"+test_list.size());
//Iterator<Test> itr=test_list.iterator();
int[] test_id=new int[test_list.size()];
for(int j=0;j<test_list.size();j++)
{
System.out.println("Test_List Import Wale me agaya");
//fields=t.getClass().getDeclaredFields();
test_id[j]=test_list.get(j).getId();
System.out.println("test_id: is "+test_id[j]);
}
System.out.println("Size of test_id array is "+test_id.length);
for(int j=0;j<test_id.length;j++)
{
System.out.println("test_id now is "+j);
int studentid=98;
String sqlquery="SELECT ST.ID id,ST.STUDENT_ID student_id,ST.attemptNumber attempt_Number,ST.TEST_ID testId,ST.TEST_ID student_test_id,T.description description,T.test_duration test_duration,T.test_score Test_Score,ST.SCHEDULED_START_TIME_BEGIN scheduled_start_time_begin,ST.SCHEDULED_START_TIME_END scheduled_start_time_end,ST.TEST_START_DATE test_start_date,ST.LAST_ACTIVE_TIME test_last_active_time,ST.TEST_ATTEMPTED test_attempted,ST.ALLOW_VIEW_REPORT allow_view_report FROM student_test as ST,test as T WHERE ST.PAYMENT_STATUS='A' AND ST.TEST_ID = T.id AND ST.STUDENT_ID='"+studentid+"' AND ST.TEST_ATTEMPTED='0' AND T.id='"+test_id[j]+"' ORDER BY ST.ID";
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/school_db","root","");
Statement pst=con.createStatement();
rs=pst.executeQuery(sqlquery);
while(rs.next())
{
//JOptionPane.showMessageDialog(null, "Table me Agaaya");
System.out.println("Number of rows:- "+rs.getRow());
System.out.println(rs.toString());
}
}
ses.getTransaction().commit();
System.out.println("Test Data Retrieved");
ses.close();
}
catch(HibernateException e)
{
e.printStackTrace();
}
}
}
this is my code and its working fine in system.out.println it showing all data now can u tell me how to pass this data in jtable and to let you know when i use dbutils its also retrieve column name automatically and i am not giving the column name in jtable manually
i know jtablename.setmodel(dbutils.setresultsettotable(rs));
Well DBUtils creates a single TableModel
but in jtable i am only getting the last loop record not every loop record
You keep replacing the old TableModel with a new TableModel.
So you have two choices:
You need to create multiple tables, one for each TableModel and add each JTable to the frame
You need to copy the data from each TableModel into a master TableModel and then display the master TableModel into in single JTable. So this means that outside of the loop your create a DefaultTableModel with just the column names and 0 rows of data. Then instead each loop your then copy each row of data from the DBUtils model to your main TableModel. Then outside the loop your create the table using the main TableModel.
Edit:
The basic structure of the code would be something like:
// Create an empty table model
String[] columnNames = {"Column1", "Column2", ...};
DefaultTableModel groupModel = new DefaultTableModel(columnNames,0);
...
// loop for all the ids
for(int j=0;j<test_id.length;j++)
{
...
// copy the data from the idc table model to the group table model
DefaultTableModel idModel = DbUtils.resultSetToTableModel(rs);
for (int i = 0; I < idModel.getRowCount())
{
Vector<Object> row = new Vector<Object>();
for (int j = 0; j < rsModel.getColumnCount()
row.addElement( rsModel.getValueAt(i, j);
groupModel.addRow( row );
}
}
JTable table = new JTable( groupModel );
Related
Good afternoon guys, i'm trying to learn java programming and then i'm encountering some problem that i don't know why with my code when I'm learning about JTable.
So, what I'm trying to do is when i double clicked the row in JTable named TableGejala, the row that i double clicked will transfered into the other JTable named TableAturan and after that the row that i double clicked in TableGejala will be removed. For the part of transferring row from TableGejala to TableAturan successfully transferred when i double clicked the row, but it doesn't delete the correct row in TableGejala. Instead of deleting the row that i clicked, it delete the row below it.
For more details, this is my code to create TableGejala :
private void getTableGejala() {
while(tabel2.getRowCount() > 0){
for(int i=0;i < tabel2.getRowCount();i++){
tabel2.removeRow(i);
}
}
tabel2.addColumn("ID Gejala");
tabel2.addColumn("Nama Gejala");
TabelGejala.setModel(tabel2);
TabelGejala.setAutoResizeMode(TabelGejala.AUTO_RESIZE_ALL_COLUMNS);
}
And then this is my code to get data for my table from MySQL :
private void loadDataGejala(Boolean baru){
tabel2.getDataVector().removeAllElements();
try {
java.sql.Connection konek = (Connection) Koneksi.KoneksiDB.getConnection();
java.sql.Statement konek_statement = konek.createStatement();
String query_bukaTabel = "";
if(baru){
query_bukaTabel = "select id_gejala,nama_gejala from gejala";
}
else{
String idPkt = FieldID.getText();
query_bukaTabel = "select gejala.id_gejala,gejala.nama_gejala from gejala where gejala.id_gejala not in(select id_gejala from aturan2 where id_penyakit='"+idPkt+"')";
}
java.sql.ResultSet line_result = konek_statement.executeQuery(query_bukaTabel);
while (line_result.next()) {
Object[] getO = new Object[2];
getO[0] = line_result.getString("id_gejala");
getO[1] = line_result.getString("nama_gejala");
tabel2.addRow(getO);
}
line_result.close();
konek_statement.close();
}catch (Exception e) {}
}
This is my code to transfer the row and delete the row :
private void TabelGejalaMousePressed(java.awt.event.MouseEvent evt) {
if (evt.getClickCount()>=2){
int col = 0;
int row = 0;
row = TabelGejala.rowAtPoint(evt.getPoint());
col = TabelGejala.columnAtPoint(evt.getPoint());
String col1 = (String)TabelGejala.getValueAt(row, 0);
String col2 = (String)TabelGejala.getValueAt(row, 1);
DefaultTableModel model = (DefaultTableModel) TabelAturan.getModel();
DefaultTableModel old = (DefaultTableModel) TabelGejala.getModel();
old.removeRow(row);
model.addRow(new Object[]{col1, col2, 0});
TabelAturan.requestFocus();
TabelAturan.setRowSelectionInterval(TabelAturan.getRowCount()-1,TabelAturan.getRowCount()-1);
TabelAturan.editCellAt(TabelAturan.getRowCount()-1,2);
}
}
And this is the screenshot of my problem :
Before Double Clicked
After Double Clicked
Which part that makes my output get the wrong row to be deleted? please help me, and thank you in advance for any helps, even for reading my question :)
Firstly disable cell editable property in your first table(TabelGejala) to ensure proper deleting of row. I achieved this using the following code :-
//instance table model
DefaultTableModel tableModel = new DefaultTableModel(new Object[][]{},
new String[]{
"ID Gejala", "Nama Gejala"
}) {
#Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
TabelGejala.setModel(tableModel);
then use jtable.getselectedrow() and jtable.getselectedcolumn() to get values from table. after addition of desired values to second table, simply delete the selected row. here is the code, derived from your code :-
private void TabelGejalaMousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
if (evt.getClickCount() >= 2) {
DefaultTableModel model = (DefaultTableModel) TabelAturan.getModel();
DefaultTableModel old = (DefaultTableModel) TabelGejala.getModel();
model.addRow(new Object[]{TabelGejala.getValueAt(TabelGejala.getSelectedRow(), 0), TabelGejala.getValueAt(TabelGejala.getSelectedRow(), 1), 0});
old.removeRow(TabelGejala.getSelectedRow());
TabelAturan.requestFocus();
TabelAturan.setRowSelectionInterval(TabelAturan.getRowCount() - 1, TabelAturan.getRowCount() - 1);
TabelAturan.editCellAt(TabelAturan.getRowCount() - 1, 2);
}
}
I am having a small problem of showing results from my database to a JTable. It displays all of the data correctly, but at the moment it is showing "true" or "false" for boolean.
I know it must be because I am using getString, but does anyone know what to use in order to change it to a checkbox instead?
Current JTable:
My Database:
Code:
connection con=new connection();
Connection getcon=null;
Vector col = new Vector();
Vector dat= new Vector();
ResultSet rs = null;
try{
getcon = con.creatConnection();
col.add("Fanta");
col.add("Crisps");
col.add("Beer");
col.add("Wine");// create income table default colum names and sore it
col.add("Water");
col.add("Seat Row");
col.add("Seat");
col.add("Total Cost");
rs=getcon.createStatement().executeQuery("select*from orders"); //getting all the information from the table
dat.clear();
while(rs.next()){// if record source avilable
Vector v =new Vector();
v.add(rs.getString("Fanta").trim());
v.add(rs.getString("Crisps").trim());
v.add(rs.getString("Beer").trim());
v.add(rs.getString("Wine").trim());// getting income values from database and store in dat
v.add(rs.getString("Water").trim());
v.add(rs.getString("SeatRow").trim());
v.add(rs.getString("Seat").trim());
v.add(rs.getString("TotalCost").trim());
dat.add(v);
}
orderResults.setModel(new DefaultTableModel(dat, col));
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
First you have to save data as a Boolean in your model. So you should use this rs.getBoolean("Fanta") instead of rs.getString("Fanta").trim().
Second, you have to override a public Class getColumnClass(int column) method from your JTable. Your code could look like this:
JTable orderResults = new JTable() {
#Override
public Class getColumnClass(int column) {
// first 5 columns will be represented as an checkbox
if(column <= 4){
return Boolean.class;
}
// rest of them as a text
return String.class;
}
};
i have a table in the database of 4rows and 4columns. each column holds a different data.
now i want to retrieve all the data in the database and put them on JLabel on another form. i.e
in my Database i have.
packageName.....monthlyFee..... YearlyFee....... TotalFee
Regular......................150..................300....................450
Gold.........................300...................400..................700
..... ..... .... ....
now i have a form that i have put 4 empty JLabels in four rows but how do i retrieve the values from the database and place each value in the appropriate Label?.
This is what i've done but i still cant get around it. im stuck.
Thank you anyone.
public void getPrices()
{
String srt ="SELECT * FROM program_tbl";
try
{
con.connect();
ps = con.con.prepareStatement(srt);
rs = ps.executeQuery();
ResultSetMetaData data = rs.getMetaData();
int colums = data.getColumnCount();
while(rs.next())
{
Vector rows = new Vector();
for (int i = 1; i < colums; i++)
{
rows.addElement(rs.getObject(i));
}
.....................................................................
If you want to get this data as a string then you could probably try something like:
Vector<String> rows = new Vector<String>();
while(rs.next()) {
String rowEntry = rs.getString("packageName") +
rs.getString("monthlyFee") +
rs.getString("yearlyFee") +
rs.getString("totalFee") +
rows.add(rowEntry);
}
If not String, but an object to use later, then you can create a class:
public class MyObject {
private String packageName;
private int monthlyFee;
private int yearlyFee;
private int totalFee;
public MyObject (String name, int monthlyFee, int yearlyFee, int totalFee) {
this.packageName = name;
this.monthlyFee = monthlyFee;
this.yearlyFee = yearlyFee;
this.totalFee = totalFee;
}
/*Setters
*And
*Getters*/
}
And then use it as:
Vector<MyObject> rows = new Vector<MyObject>();
while (rs.next()) {
MyObject obj = new MyObject(rs.getString("packageName")
, rs.getInt("montlyFee")
, rs.getInt("yearlyFee")
, rs.getInt("totalFee")
);
rows.add(obj)
}
So say we now have a vector with String values - Vector<String> rows;
now i would like to create those JLabels.
JLabel[] myLabels = new JLabel[v.size()];
for(int i=0; i<rows.size(); i++) {
as[i] = new JLabel(rows.get(i));
}
And now we have an array of JLabels ready to be put to applet.
Don't use a JLabel. There is no way you can easily format the data so that you get tabular data.
Instead you should be using a JTable. Read the section from the Swing tutorial on How to Use Tables for more information. You can also search the forum for examples of using a JTable with a ResultSet.
Adding the colums works, but i am stuck when i want to add the data of the columns stored in a mysql database to the jtable. it ask for a object vector[][] but i have no clue what to give
Connection con;
DefaultTableModel model = new DefaultTableModel();
public Hoofdscherm() {
initComponents();
uitvoerSpelers.setModel(model);
try {
con = DriverManager.getConnection("jdbc:mysql://localhost/fullhouse", "root", "hamchi50985");
// selecteer gegevens uit fullhouse.speler tabel
PreparedStatement stat = con.prepareStatement("SELECT * FROM fullhouse.speler");
// sla deze GEGEVENS op in een resultset
ResultSet resultaat = stat.executeQuery();
// haal alle kolomnamen op PUUR VOOR DE MODEL VAN JTABLE
ResultSetMetaData data = resultaat.getMetaData();
String[] colum = new String[15];
for (int i = 1; i < data.getColumnCount(); i++) {
colum[i] = data.getColumnName(i);
model.addColumn(colum[i]);
while (resultaat.next()) {
Object[] gegevens = new String[] {resultaat.getString(1)};
model.addRow(gegevens[0]);
}
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
I think you need something like this.
Note
1. Also add your columns separate to resultset data. Like I showed in my code below.
Vector<String> rowOne = new Vector<String>();
rowOne.addElement("R1C1");
rowOne.addElement("R1C2");
Vector<String> rowTwo = new Vector<String>();
rowTwo.addElement("R2C1");
rowTwo.addElement("R2C2");
Vector<String> cols = new Vector<String>();
Vector<Vector> vecRow = new Vector<Vector>();
vecRow.addElement(rowOne);
vecRow.addElement(rowTwo);
cols.addElement("Col1");
cols.addElement("Col2");
JTable table = new JTable(vecRow, cols);
Edit
For you convenience and requirement You can follow code structure below.
Vector<String> rows = new Vector<String>();
Vector<Vector> dBdata = new Vector<Vector>();
// Add Columns to table
for (int i = 1; i < data.getColumnCount(); i++) {
colum[i] = data.getColumnName(i);
model.addColumn(colum[i]);
}
while (resultaat.next()) {
// add column data to rows vector
// Make sure that all data type is in string because of generics
rows.add(resultaat.getString("columnName1"));
rows.add(resultaat.getString("columnName2"));
rows.add(resultaat.getString("columnName3"));
// add whole row vector to dBdata vector
dBdata.addElement(rows);
}
model.addRow(dBdata);
Vector implements a dynamic array. It is similar to ArrayList, but with two differences:
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework.
Class Vector Javadoc
I hope this will help you.
The line model.addRow(gegevens[0]);is incorrect.
You should do something like this:
String[] colum = new String[15];
for (int i = 1; i < data.getColumnCount(); i++) {
colum[i] = data.getColumnName(i);
model.addColumn(colum[i]);
while (resultaat.next()) {
Object[] gegevens = new String[] {resultaat.getString(1)};
model.addRow(gegevens);
}
}
Also you need to check DefaultTableModel
According to the documentation of DefaultTableModel:
This is an implementation of TableModel that uses a Vector of Vectors
to store the cell value objects.
I'm trying to populate a table with data from a database however i am having some issues with it. Could someone provide me with an example? (so the table takes in an Object[][] parameter for the data). I have the following basic code to display a table ;
class table extends JFrame
{
JTable table;
public table()
{
setLayout(new FlowLayout());
String[] columnNames = {"test","test","test"};
Object[][] data= {{"test","test","test"},{"test","test","test"}};
table = new JTable(data,columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500,100));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
}
Two years ago, during my time in technical school, I wrote a little library help solve some of the problems proposed by the exercises, which included a a DatabaseTableModel.
The class extends from AbstractTableModel, which means you can set it as the your JTable's data source.
Here's the algorithm that constructs a model from a ResultSet:
public final void constructModel(ResultSet rs) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
rs.last();
rowCount = rs.getRow();
int columnCount = rsmd.getColumnCount();
// DatabaseColumn simply holds a name and a Class<?>.
columns = new DatabaseColumn[columnCount];
// This is the Object[][] array that you were talking about.
// It holds all the data from the ResultSet.
data = new Object[columnCount][rowCount];
for (int i = 0; i < columnCount; ++i) {
// Figure out the column name and type.
int j = i + 1;
String colName = rsmd.getColumnLabel(j);
Class<?> colClass = String.class;
try {
colClass = Class.forName(rsmd.getColumnClassName(j));
} catch (ClassNotFoundException ex) {
colClass = String.class;
}
columns[i] = new DatabaseColumn(colName, colClass);
// Get the data in the current column as an Object.
rs.beforeFirst();
for (int k = 0; rs.next(); ++k) {
data[i][k] = rs.getObject(j);
}
}
// Notify listeners about the changes so they can update themselves.
fireTableStructureChanged();
}
The class worked when I used it in school, but it isn't exactly production code. When I look at it today, I start to see problems.
One problem is that it is loading the entire contents of the ResultSet into memory. Could get ugly pretty quickly.
Also, the algorithm isn't exactly optimal. It loops around with the database cursor as if it was nothing; I suppose that it would be less costly for the database if it had retrieved all the objects in the current row first and assigned them to their appropriate columns before moving on to the next row.
Nevertheless, I think it is a good enough starting point.