I have created 2 JTable in my class,
for the first JTable the data comes from server to arraylist and then to JTable
for the second JTable the data comes from local access database to JTable (no arraylist)
Both JTables will be displayed together when user click a button.
But it takes up to 1min to load and display both jtable on the interface.
Is there any way to load them faster?
Sample code Table1
data = new ArrayList<Person>();
try
{
conn = dc.getConnection();
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
while(rs.next())
{
String[] rowData = new String[4];
for(int i=1;i<=4;i++)
{
rowData[i-1] = rs.getString(i);
}
//database to arraylist
data.add(new Person(rowData[0],rowData[1],rowData[2],rowData[3]));
}
String[] colNames = {"LastName","FirstName","Email","Department"};
model = new DefaultTableModel(colNames,data.size())
sorter = new TableRowSorter<TableModel>(model);
int row = 0;
//arraylist to JTable
for(Person p:data)
{
model.setValueAt(p.lastName, row, 0);
model.setValueAt(p.firstName, row, 1);
model.setValueAt(p.email, row, 2);
model.setValueAt(p.dept, row, 3);
row++;
}
table.setModel(model);
table.setRowSorter(sorter);
Sample code of Table2
String[] colNames = {"Name","Email","Department","Status"};
model = new DefaultTableModel(colNames,500);
table.setModel(model);
try
{
conn = ac.getConnection();
stmt = conn.prepareStatement(insert);
rs = stmt.executeQuery();
int row = 0;
while(rs.next())
{
String[] rowData = new String[4];
for(int i=1;i<=4;i++)
{
rowData[i-1] = rs.getString(i);
}
//access database to jTable
model.setValueAt(rowData[0], row, 0);
model.setValueAt(rowData[1], row, 1);
model.setValueAt(rowData[2], row, 2);
model.setValueAt(rowData[3], row, 3);
row++;
}
The delay is caused by the time required to do the database queries. So you want to make sure you are doing two separate queries, each on a different thread so one query is not waiting for the other to finish.
This can be done by creating 2 SwingWorkers, one for the server access and the other for the local access.
you can load data to jtable easily through this
DefaultTableModel tm = (DefaultTableModel) jTable1.getModel();
tm.addRow(new Object[] {name,age,tel});
name age tel are values in column1, column2, column3
Related
I am trying to get data from a database and display them into a JTable in Java.
Now I have a working code which does retrieve the data and displays it in the table but somehow it does not display the first column. Anybody an idea?
Here my code:
stmt = con.createStatement();
rs = stmt.executeQuery(Query);
while (table.getRowCount() > 0) {
((DefaultTableModel) table.getModel()).removeRow(0);
}
int columns = rs.getMetaData().getColumnCount();
while (rs.next()) {
Object[] row = new Object[columns];
for (int i = 1; i <= columns; i++) {
row[i-1] = rs.getObject(i);
}
((DefaultTableModel) table.getModel()).insertRow(rs.getRow() - 1, row);
}
rs.close();
stmt.close();
con.close();
UPDATE
Ok I tried using Vector and it happens the same thing. My database has the following columns: ID, Subject, AS1, AS2
Now I do get the data displayed in the JTable, but the order of my row data always starts with the Subject column first, then AS1, then AS2 and last ID.
Why is this happening?
I have found a way around it by creating another Object[] and assigning the last object from the first array to the first of array two.
while (rs.next()) {
Object[] row = new Object[columns];
for (int i = 1; i <= columns; i++) {
row[i-1] = rs.getObject(i);
}
Object sub = row[0];
Object ses = row[1];
Object as1 = row[2];
Object as2 = row[3];
Object as3 = row[4];
Object fe = row[5];
Object id = row[6];
Object[] row2 = new Object[columns];
row2[0] = id;
row2[1] = sub;
row2[2] = ses;
row2[3] = as1;
row2[4] = as2;
row2[5] = as3;
row2[6] = fe;
((DefaultTableModel) table.getModel()).insertRow(rs.getRow() - 1, row2);
}
Not beautiful but it gets the job done.
How to display MySQL data in JTable without using vector?
I'm doing Java Swing application and I want to show reports from database. I'm using JTable to display data from database. I have tried following code but it is not displaying data from database. My database connection is also correct.
int i;
static Vector<Vector<String>> data = new Vector<Vector<String>>();
String[] columnNames = {"Registration id", "First Name", "Middle Name", "Last Name", "Address", "Dob", "Age", "Date Of Registration", "Register Rfid No."};
public AdmissionReport()
{
initComponents();
//this is the model which contain actual body of JTable
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
//jTable1=new JTable(model);
jTable1 = new JTable();
jTable1.setModel(model);
int i1 = jTable1.getRowCount();
if (i1 > 1) {
model.removeRow(0);
i1 = i1 - 1;
}
String str = "select rid,fname,mname,lname,address,dob,age,dor,rfidtagdata from schoolrfid.registration";
Connection cn;
ResultSet rs;
Statement st;
String rid, fname, mname, lname, add, dob, age, dor, rfidtag;
try {
// Change the database name, hosty name,
// port and password as per MySQL installed in your PC.
cn = DriverManager.getConnection("jdbc:mysql://" + "localhost:3306/schoolrfid", "root", "root");
st = cn.createStatement();
rs = st.executeQuery(str);
System.out.println("connected to database.. ");
// int i=0;
while (rs.next()) {
//Vector <String> d=new Vector<String>();
rid = (rs.getString("rid"));
fname = (rs.getString("fname"));
mname = (rs.getString("mname"));
lname = (rs.getString("lname"));
add = (rs.getString("address"));
dob = (rs.getString("dob"));
age = (rs.getString("age"));
dor = (rs.getString("dor"));
rfidtag = (rs.getString("rfidtagdata"));
i = 0;
String[] data = {rid, fname, mname, lname, add, dob, age, dor, rfidtag};
model.addRow(data);
i++;
}
if (i < 1) {
JOptionPane.showMessageDialog(null, "No Record Found", "Error", JOptionPane.ERROR_MESSAGE);
}
if (i == 1) {
System.out.println(i + " Record Found");
} else {
System.out.println(i + " Records Found");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
The TableModel behind the JTable handles all of the data behind the table. In order to add and remove rows from a table, you need to use a DefaultTableModel
To create the table with this model:
JTable table = new JTable(new DefaultTableModel(new Object[]{"Column1", "Column2"}));
To add a row:
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[]{"Column 1", "Column 2", "Column 3"});
You can also remove rows by removeRow(int row) which will removes the row at row from the model.
Full details on the DefaultTableModel can be found here
Similarly from the MySQL you can add rows like as show below
DefaultTableModel memberTable = (DefaultTableModel) table.getModel();
while(rs.next())
{
memberTable.addRow(new Object[]{rs.getString('rid'),rs.getString('fname'),rs.getString('lname'),rs.getString('address'),.....});
}
Also Take a look at this answer
https://stackoverflow.com/a/17655017/1575570
I want to put an action whenever someone clicks a cell. open another gui for example. But how do i make a cell clickable BUT not editable? These are results for an sql query. I can't manage to make the table uneditable though. Do I need a listener or something? and if yes where should I put it?
Here is my code:
public class AllResultsFromDB extends JFrame
{
GUI ins = new GUI();
public AllResultsFromDB(GUI x)
{
Vector columnNames = new Vector();
Vector data = new Vector();
this.ins = x;
try
{
// Initializing GUI class in order to call getSelectedTable() method.
// GUI ins = new GUI();
//System.out.println(ins.getSelectedTable());
Login sgui = new Login();
String dburl = "jdbc:oracle:thin:#localhost:1521:ORCL";
Connection connection = DriverManager.getConnection( dburl, sgui.getUsername(), sgui.getPassword() );
// Fetch data from table specified by user
String query = "SELECT * FROM " + ins.getSelectedTable() + " ORDER BY id";
System.out.println(query);
Statement stmt = connection.createStatement();
ResultSet rset = stmt.executeQuery(query);
ResultSetMetaData metad = rset.getMetaData();
int columns = metad.getColumnCount();
// This loop gets the names of the columns
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( metad.getColumnName(i) );
//columnNames.addElement("PROFILES");
}
// This loop gets the data inside the rows
while (rset.next())
{
Vector row = new Vector(columns);
//Vector b = new Vector((Collection)button);
for (int i = 1; i <= columns; i++)
{
row.addElement( rset.getObject(i) );
}
data.addElement( row );
//data.addElement(b);
}
rset.close();
stmt.close();
connection.close();
// Create table with results
JTable table = new JTable(data, columnNames)
{
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object obj = getValueAt(row, column);
if (obj != null)
{
return obj.getClass();
}
}
return Object.class;
}
};
JScrollPane scroll = new JScrollPane( table );
getContentPane().add( scroll );
//table.addMouseListener(l);
//table.setEnabled(false);
//table.setDragEnabled(true);
JPanel panel = new JPanel();
getContentPane().add( panel, BorderLayout.SOUTH );
} catch (SQLException e) {
}
}
}
Start by taking a look at How to use tables
The isCellEditable method the TableModel determines of a cell is editable or not. This method should return false
When you supply column/data information to the JTable directly, the JTable creates a DefaultTableModel internally. This class's isCellEditiable method will return true by default.
By using something like DefaultTableModel, you can override this method without with to much trouble and set the model to the table directly.
Next, you need to attach a MouseListener to the table
Take a look at How to write a Mouse Listener
You can then use getSelectedColumn, getSelectedRow to get the selected cell.
You'll also need to use convertRowIndexToModel and convertColumnIndexToModel to convert between the view and model indices
Could someone provide me with an example or tutorial on how to import a data from a mysql database within a JTable within the use of a GUI. I tried looking for an example but have not found anything.
Hopefully we can put this question to rest
Connection db = DriverManager.getConnection( jdbc:mysql://192.168.0.3:3306,<user>,<password>);
Statement stmt = db.createStatement();
PreparedStatement psmt = con.prepareStatement("SELECT * FROM DB");
ResultSet rs = psmt.executeQuery();
// get column names
int len = rs.getMetaData().getColumnCount();
Vector cols= new Vector(len);
for(int i=1; i<=len; i++) // Note starting at 1
cols.add(rs.getMetaData().getColumnName(i));
// Add Data
Vector data = new Vector();
while(rs.next())
{
Vector row; = new Vector(len);
for(int i=1; i<=len; i++)
{
row.add(rs.getString(i));
}
data.add(row);
}
// Now create the table
JTable table = new JTable(data, cols);
How to display ResultSet in JTable. i am using this code
String [] record= new
String[ColCount];
for (i=0; i<ColCount; i++)
{
record[i]=rset1.getString(i+1);
}
cell[i] = rset1.getString("loginname");
cell[i] = rset1.getString( "role");
System.out.println(cell[i][0]);
//ItemGroup = rset1.getString( "Status");
}
System.out.println(ItemCode);
JTable jt = new JTable(
cell[i], headers);
but I get only one row which is lastly inserted to database.
You need to put a while loop around your code to iterate over the result set. eg,
while(rset1.next())
{
//do something
}
The code that you have listed is incomplete/incomprehensible, but the code below shows how to take a ResultSet with an arbitrary number of columns and display its contents in a JTable.
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
private void viewTable(){
//Perform database query here, which will open a Connection to the database
//Assume we use the above query to populate a ResultSet results
//Get information about the ResultSet
ResultSetMetaData metaData = results.getMetaData();
//Gets the number of columns in results
int columnCount = metaData.getColumnCount();
//Gets the name of each column in results
String[] columnNames = new String[columnCount];
for(int i = 0; i < columnNames.length; i++){
columnNames[i] = metaData.getColumnLabel(i+1);
}
//You can use a String[] to keep track of the rows if you know the #
//# of rows in the ResultSet, this implementation assumes that we don't
//This ArrayList will keep track of each row in results (each row is
//represented by a String[]
ArrayList<String[]> rows = new ArrayList<>();
while(results.next()){
//Fetch each row from the ResultSet, and add to ArrayList of rows
String[] currentRow = new String[columnCount];
for(int i = 0; i < columnCount; i++){
//Again, note that ResultSet column indecies start at 1
currentRow[i] = results.getString(i+1);
}
rows.add(currentRow);
}
//Close Connection to the database here
String[][] rowsArray = new String[rows.size()][columnCount];
rowsArray = rows.toArray(rowsArray);
table = new JTable(rowsArray, columnNames);
}