how to populate data into JTable

need help in populating data in JTable and displaying it .

Page 1 of 1

5 Replies - 8708 Views - Last Post: 03 April 2010 - 07:56 PM Rate Topic: -----

#1 ghkashyap  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 1
  • Joined: 08-January 08

how to populate data into JTable

Posted 08 January 2008 - 01:46 AM

public class TransactionsModel extends DefaultTableModel implements
		ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	JTable table;
	int myColCount;

	// JTextField txtfld;
	// Constructor. This connects to the database retrieves
	// data based on the stored procedure and populates the JTable in TransactionsView

	TransactionsModel() {
	}

	TransactionsModel(JTextField accountnum) {
		// myColCnt stores the columnCount.
		int myColCnt = 0;

		try {
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		ResultSet rs = null;
		Connection con = null;

		try {
			con = DriverManager.getConnection("jdbc:odbc:oracle", "scott",
					"tiger");
		} catch (Exception ignored) {
			System.out.println("Error in getting Connection");
			ignored.printStackTrace();
		}

		try {
			Statement stmt = con.createStatement();
			rs = stmt
					.executeQuery("SELECT * FROM TRANSACTIONS WHERE ACCOUNT_NO='"
							+ accountnum.getText() + "'");
		} catch (Exception ignored) {
		}

		try {
			myColCnt = rs.getMetaData().getColumnCount();
		} catch (SQLException sexcpt) {
			System.out.println("Error in getting column count : "
					+ sexcpt.getMessage());
		}
		try {
			for (int i = 1; i <= myColCnt; i++)

			{
				// System.out.println("entered loop");
				columnIdentifiers.addElement(rs.getMetaData().getColumnName(i));
				// System.out.println("after colidentifiers");
			}
			
		} catch (Exception ignored) {
			System.out.print("Exception caught");
			ignored.printStackTrace();
		}
		
		Vector row = new Vector();
		try {
			while (rs.next()) {
				row = new Vector();
				for (int i = 1; i <= myColCnt; i++) {
					row.addElement(rs.getObject(i));
				}
				
				dataVector.addElement(row);

			}
			
		}

		catch (Exception ignored) {
		}

	}

	public void actionPerformed(ActionEvent ae) {
		
		

	}

}

~edit: code tags PB
*********************
this is the view class which has to display data OF THE JTable.the model is retriving the data but i am facing problem in displaying it. when i print the dataVector its is showing all the retrived values from the table in the DB.but how to display this data is wat that i am concerned about.
please help
thanks in advance...
harish.

This post has been edited by PennyBoki: 08 January 2008 - 11:03 AM


Is This A Good Question/Topic? 1

Replies To: how to populate data into JTable

#2 aliasgon  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 10-April 09

Re: how to populate data into JTable

Posted 10 April 2009 - 07:12 AM

View Postghkashyap, on 8 Jan, 2008 - 12:46 AM, said:

public class TransactionsModel extends DefaultTableModel implements
		ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	JTable table;
	int myColCount;

	// JTextField txtfld;
	// Constructor. This connects to the database retrieves
	// data based on the stored procedure and populates the JTable in TransactionsView

	TransactionsModel() {
	}

	TransactionsModel(JTextField accountnum) {
		// myColCnt stores the columnCount.
		int myColCnt = 0;

		try {
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		ResultSet rs = null;
		Connection con = null;

		try {
			con = DriverManager.getConnection("jdbc:odbc:oracle", "scott",
					"tiger");
		} catch (Exception ignored) {
			System.out.println("Error in getting Connection");
			ignored.printStackTrace();
		}

		try {
			Statement stmt = con.createStatement();
			rs = stmt
					.executeQuery("SELECT * FROM TRANSACTIONS WHERE ACCOUNT_NO='"
							+ accountnum.getText() + "'");
		} catch (Exception ignored) {
		}

		try {
			myColCnt = rs.getMetaData().getColumnCount();
		} catch (SQLException sexcpt) {
			System.out.println("Error in getting column count : "
					+ sexcpt.getMessage());
		}
		try {
			for (int i = 1; i <= myColCnt; i++)

			{
				// System.out.println("entered loop");
				columnIdentifiers.addElement(rs.getMetaData().getColumnName(i));
				// System.out.println("after colidentifiers");
			}
			
		} catch (Exception ignored) {
			System.out.print("Exception caught");
			ignored.printStackTrace();
		}
		
		Vector row = new Vector();
		try {
			while (rs.next()) {
				row = new Vector();
				for (int i = 1; i <= myColCnt; i++) {
					row.addElement(rs.getObject(i));
				}
				
				dataVector.addElement(row);

			}
			
		}

		catch (Exception ignored) {
		}

	}

	public void actionPerformed(ActionEvent ae) {
		
		

	}

}

~edit: code tags PB
*********************
this is the view class which has to display data OF THE JTable.the model is retriving the data but i am facing problem in displaying it. when i print the dataVector its is showing all the retrived values from the table in the DB.but how to display this data is wat that i am concerned about.
please help
thanks in advance...
harish.



 public void searchnow(String cb,String bc) { 
		String string = "SELECT ID,LastName,FirstName,Course,MSince,Status "
				+ "FROM tblPersonal WHERE "
				+cb+  "=" + "'"+bc+"'";
		datacon search = new datacon(); //this I use to connect 2 database
		if (search.db_connection!=null) {
			search.closeConnection(1);
		}
		else {
			search.datacon();
			search.connectToDB();
			search.createStatement(true);
		}
		
		try {
								result = search.db_statement.executeQuery(string);
								 DefaultTableModel dtm = new DefaultTableModel();
								 int ColCnt = result.getMetaData().getColumnCount();

									for (int i = 1; i <= ColCnt; i++)
									{
									 columnIdentifiers.addElement(result.getMetaData().getColumnName(i));
									}
								 Vector row = new Vector();
								 while (result.next()) {
									row = new Vector();
									for (int i = 1; i <= ColCnt; i++) {
									row.addElement(result.getObject(i));
									}
									dataVector.addElement(row);

								 }
								dtm.setDataVector(dataVector, columnIdentifiers);
								new SearchResultForm(dtm).setVisible(true);

							}
							catch (SQLException sqle) {
								JOptionPane.showMessageDialog(null,"Error on SQL "+sqle);
							}
	}//end of searchnow method


dtm.setDataVector(dataVector, columnIdentifiers);
new SearchResultForm(dtm).setVisible(true);


i just use this code to set the new table and pass it to a different form that holds the JTable i already have and set its .setModel to the table "dtm".

the SearchResultForm() accepts a defaulttablemodel, so i just pass "dtm into it.

oh and i set the code nameofjtable.setModel(variable u specify) after the init() if the jtable so it would load immediately the contents.

hope it helps. nways your code helped me a lot. thanks
Was This Post Helpful? 0
  • +
  • -

#3 Guest_suryaprakash*


Reputation:

Re: how to populate data into JTable

Posted 03 April 2010 - 06:48 AM

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.io.*;
import java.util.*;
import java.sql.*;
//**************************************************************************
class guiDATA_TABLE_EDITOR extends JFrame{
//**************************************************************************
private JPanel panel;
private String[] colDATA = {"NAME","AGE","SEX","EDUCATION","EXTRA","SALARY","FIELD","LOGIN","PASSWORD"};
private DefaultTableModel dtmDATA;
private JTable tblDATA;
private JScrollPane sbrDATA;

private JButton btnCANCEL; 
private Insets insets;
private String wrkCONSTR="jdbc:odbc:go";
 
//-------------------------------------------------------------------------- 
public guiDATA_TABLE_EDITOR(){ //Define GUI Controls & Properties
//-------------------------------------------------------------------------- 
setTitle("JAVA Data Table Editor"); 
setBounds(250,150,655,450);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
panel = new JPanel();
panel.setLayout(null);
insets = panel.getInsets();
this.add(panel);
 
dtmDATA = new DefaultTableModel(20,6); 
tblDATA = new JTable(dtmDATA); 
TableColumn c = null;
c = tblDATA.getColumnModel().getColumn(0);
c.setPreferredWidth(100);
c.setHeaderValue("NAME");
c = tblDATA.getColumnModel().getColumn(1);
c.setPreferredWidth(100);
c.setHeaderValue("AGE");
c = tblDATA.getColumnModel().getColumn(2);
c.setPreferredWidth(100);
c.setHeaderValue("SEX"); 
//c.setEditable(false); 
c = tblDATA.getColumnModel().getColumn(3);
c.setPreferredWidth(100);
c.setHeaderValue("EDUCATION");
c = tblDATA.getColumnModel().getColumn(4);
c.setPreferredWidth(100); 
c.setHeaderValue("EXTRA"); 
c = tblDATA.getColumnModel().getColumn(5);
c.setPreferredWidth(130); 
c.setHeaderValue("SALARY"); 
 
tblDATA.setBackground(new Color(180,180,255)); 
tblDATA.setBorder(BorderFactory.createLineBorder(Color.BLACK)); 
sbrDATA = new JScrollPane(tblDATA,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); 
sbrDATA.setBounds(insets.left + 10,insets.top + 10,630,360);
panel.add(sbrDATA); 
buildTable(); 
 
 
btnCANCEL = new JButton("Cancel");
btnCANCEL.setBounds(insets.left + 400,insets.top + 375,100,35);
btnCANCEL.setBorder(BorderFactory.createRaisedBevelBorder());
btnCANCEL.addActionListener(new ButtonHandler()); 
panel.add(btnCANCEL); 
}
 
//----------------------------------------------------------------------------- 
private void buildTable(){ //Populate table rows with recordset fields.
//----------------------------------------------------------------------------- 
String wrkSQL="SQL "; int R=0;
try{ 
//Set up database Conection.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection(wrkCONSTR); 
wrkSQL="Select * from Applicant";
//Set up database SQL stament & recordset string. 
Statement s = con.createStatement();
s.execute(wrkSQL);
ResultSet rs = s.getResultSet();
//Populate Table 

if (rs != null) { 
while (rs.next()){
if (R>=tblDATA.getRowCount()) {
dtmDATA.addRow(new Object[] {"","","","","","",""});
} 
dtmDATA.setValueAt(rs.getString("Name"),R,0);
dtmDATA.setValueAt(rs.getString("Age"),R,1);
dtmDATA.setValueAt(rs.getString("Sex"),R,2); 
dtmDATA.setValueAt(rs.getString("Education"),R,3);
dtmDATA.setValueAt(rs.getString("Extra"),R,4);
dtmDATA.setValueAt(rs.getString("Salary"),R,5); 
R=R+1;
}
}
s.close(); con.close();
//Populate empty rows for adding records.
if (R >= (tblDATA.getRowCount()-10)) {
for (int x=0; x<10; x++){
dtmDATA.addRow(new Object[] {"","","","","","",""});
}
} 
 
}
catch (Exception err){
System.out.println("BUILD ERROR: " + err);
}
} 
 
//-----------------------------------------------------------------------------
private class ButtonHandler implements ActionListener{ //Button Event.
//-----------------------------------------------------------------------------
public void actionPerformed(ActionEvent e) {
JButton b = (JButton)e.getSource(); 
 if (b==btnCANCEL) {
dispose();
} 
}
}
 
//-----------------------------------------------------------------------------

 
public static void main(String[] args) { //Startup program
//--------------------------------------------------------------------------
guiDATA_TABLE_EDITOR gui = new guiDATA_TABLE_EDITOR();
gui.setVisible(true); 
} 
 
}



Edited by Dogstopper: :code: and seriously work on indenting!

This post has been edited by Dogstopper: 03 April 2010 - 08:17 AM

Was This Post Helpful? 0

#4 m-e-g-a-z  Icon User is offline

  • Winning
  • member icon


Reputation: 496
  • View blog
  • Posts: 1,453
  • Joined: 19-October 09

Re: how to populate data into JTable

Posted 03 April 2010 - 06:56 AM

Why bring a post up from 10 April 2009 ??


If you have any issues/help with your code, we wil be more than happy to help you but in future,
please dont bring up other peoples posts that are a nearly a year old.

This post has been edited by m-e-g-a-z: 03 April 2010 - 07:00 AM

Was This Post Helpful? 0
  • +
  • -

#5 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2870
  • View blog
  • Posts: 11,021
  • Joined: 15-July 08

Re: how to populate data into JTable

Posted 03 April 2010 - 08:19 AM

As m-e-g-a-z mentioned, it is a bad habit to post in old topics, even if you may have something to contribute, but this post isn't all that old...just a year. However, I thank you for your contribution.

If you need help, please start your own topic.
Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: how to populate data into JTable

Posted 03 April 2010 - 07:56 PM

As this thread dated from 2008 I'll close it

Just as a comment, YOU DO NOT populate data in a JTable
JTable are just a fancy GUI interface that displays data held by it's model
so you just let the JTable to display the data you want it to display
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1