JTable Problems
Hi,
I am working on a search page which searches for details in my database.
I had managed to get details from the database and display out in a JTable.
However when I click on the search button after the 2nd time, the previous result would not go away and it's just add on.
1) how do i replace the previous search result with the new one?
2) my rows and columns keep multiping.i want to fix the columns shown in my table.
My codes are shown below:
if(event.getSource() == SearchButton)
{
String searchid=txtsearch.getText();
//Connecting to database for retrival
String data ="jdbc:mysql://localhost:3306/mydata";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(data,"root","admin");
Statement st = conn.createStatement();
ResultSet rec = st.executeQuery("SELECT * FROM fruits WHERE fruitID LIKE '"+searchid+"%'");
ResultSetMetaData md = rec.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( md.getColumnName(i) );
}
// Get row data
while (rec.next())
{
Vector row =new Vector(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rec.getObject(i) );
}
datas.addElement( row );
}
rec.close();
st.close();
}
catch (SQLException s){
System.out.println("SQL Error: " + s.toString() +" "+ s.getErrorCode() +" " + s.getSQLState());
}
catch (Exception e){
System.out.println(" Error: " + e.toString() + e.getMessage());
}
// Create table with database data
table =new JTable(datas, columnNames);
JScrollPane scrollPane =new JScrollPane( table );
scrollPane.setPreferredSize(new Dimension(300, 300));
getContentPane().add( scrollPane );
scrollPane.setBounds (115,350,800, 200);
table.getTableHeader().setReorderingAllowed(false);
table.getTableHeader().setResizingAllowed(false);
}
I am aware the 2 FOR loops are the reason why my multiples columns and rows are creating, however is there any way to fix it to what i mentioned above.?
i know it possible buti just don't know how..
Thanks.Would appreciate any help.
[3667 byte] By [
Krissa] at [2007-10-2 10:19:40]

Don't create a new table, just replace the model:DefaultTableModel model = new DefaultTableModel(....);table.setModel( model );
Hi,i don't get what you mean..can you please explain more..if possible,please show me an example.thanks.
> i don't get what you mean..can you please explain more..
Data is stored in a TableModel. So if you want to change the data that is displayed in the table you don't need to create a new JTable. Just create a new TableModel and reset the TableModel that is used by the table.
Here's a working example:
http://forum.java.sun.com/thread.jspa?forumID=31&threadID=619826
Use this code instead of your earlier code
if(event.getSource() == SearchButton)
{
String searchid=txtsearch.getText();
//Connecting to database for retrival
String data = "jdbc:mysql://localhost:3306/mydata";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(data, "root", "admin");
Statement st = conn.createStatement();
ResultSet rec = st.executeQuery("SELECT * FROM fruits WHERE fruitID LIKE '"+searchid+"%'");
ResultSetMetaData md = rec.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( md.getColumnName(i) );
}
// Get row data
while (rec.next())
{
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rec.getObject(i) );
}
datas.addElement( row );
}
rec.close();
st.close();
}
catch (SQLException s) {
System.out.println("SQL Error: " + s.toString() + " "+ s.getErrorCode() + " " + s.getSQLState());
}
catch (Exception e) {
System.out.println(" Error: " + e.toString() + e.getMessage());
}
// Create table with database data
//See the changes to the code start here
if(table==null)
table = new JTable(datas, columnNames);
else
table.setModel(new DefaultTableModel(datas,columnNames);
//Changes to the code ends here
JScrollPane scrollPane = new JScrollPane( table );
scrollPane.setPreferredSize(new Dimension(300, 300));
getContentPane().add( scrollPane );
scrollPane.setBounds (115,350,800, 200);
table.getTableHeader().setReorderingAllowed(false);
table.getTableHeader().setResizingAllowed(false);
}
Hi all,
thanks for all your prompt reply.
I had tried all your methods listed but to no avil. my rows and columns are still multipling when i click the button.
say i got 2 column with ID and name.
FruitID | FruitName (display on first click)
FruitID | FruitName | FruitID | FruitName (display on second click)
This is what my problem is.. the rows and columns keep duplicating.
any way to solve?
Camickr--> i had tired the default tablemodel way..
Codes as shown below:
ResultSetMetaData md = rec.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( md.getColumnName(i) );
}
// Get row data
while (rec.next())
{
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rec.getObject(i) );
}
datas.addElement( row );
}
// Reset Table
DefaultTableModel model = new DefaultTableModel(datas, columnNames);
table.setModel( model );
rec.close();
st.close();
}
CSJahkaria: I had also tried your way but it still doesn't solve the problem.
ANy idea?
> the rows and columns keep duplicating.This means the Vectors keep growing in size.I gave you working code. Compare your code with mine to see what the difference is.
HI, had tried your codes. Compiled successfully but when run there is a NULLPOINTEREXCEPTION.
also, i can't relate your working example to mine. I only understand the displayTableColumn method but the above part, i don't quite understand.
Like what is a catalog? Y i need to use a combobox etc..
I am creating a search page. I can search successfully but just that my rows and columns keep duplicating when i display the data out in a JTable.
At first i thought i just need to reset the table in a table model.but that doesn't seems the case.
// Reset Table
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table.setModel( model );
Is there anything i missed out?
Your columns keep duplicating because each time the actionPerformed(...) method is invoked, you keep on adding the column to the columnNames Vector.
Your rows keep duplicating because the table model was never reset. If you are using DefaultTableModel, there is a setRowCount(...) method that you can make use of.
Here's an example provided for your reference. You prabably need to do some validation on the field input, and display some search result message. Otherwise, it is working fine.
import java.sql.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class DatabaseTableTest extends JFrame implements ActionListener {
private JTextField textField;
private DefaultTableModel model;
private Object[] columnNames = {"Fruit ID", "Fruit Name"};
private Connection cn = null;
public DatabaseTableTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
model = new DefaultTableModel(columnNames, 0);
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
JPanel panel = new JPanel();
textField = new JTextField(10);
JButton button = new JButton("Search");
button.addActionListener(this);
panel.add(textField);
panel.add(button);
getContentPane().add(scrollPane);
getContentPane().add(panel, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
String id = textField.getText();
String url = "jdbc:mysql://localhost:3306/mydata";
if (cn == null) {
try {
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection(url, "root", "admin");
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
try {
Vector data = new Vector();
Vector row = null;
Statement st = cn.createStatement();
String sql = "SELECT * FROM fruits WHERE fruitid LIKE '" + id + "%'";
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
while (rs.next()) {
row = new Vector(columns);
for (int x = 1; x <= columns; x++ ) {
row.addElement(rs.getObject(x));
}
data.addElement(row);
}
rs.close();
st.close();
model.setRowCount(0);
for (int x = 0; x < data.size(); x++) {
model.addRow((Vector)data.elementAt(x));
}
} catch (Exception e) { e.printStackTrace(); }
}
public static void main(String[] args) { new DatabaseTableTest(); }
}
Hi all,thanks ajneo,camikir and all who had responded to help me.I managed to solve the problem now.You guys respond had one way or another help me to undertsand the problem better.thanks.
hi friend i am also facing same problem can u pass the code what u r writing.
i am also doing searching option when i click first time ok if i click 2nd time duplicate values are storing into JTable. will u please help me any body.
i am sending my code below..
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(evt.getSource() == jButton1)
showEmployerDetails();
}
public void showEmployerDetails(){
TableColumn col = jTable1.getColumnModel().getColumn(0);
TableColumn col1 = jTable1.getColumnModel().getColumn(1);
TableColumn col2 = jTable1.getColumnModel().getColumn(2);
TableColumn col3 = jTable1.getColumnModel().getColumn(3);
TableColumn col4 = jTable1.getColumnModel().getColumn(4);
col.setPreferredWidth(300);
col1.setPreferredWidth(150);
col2.setPreferredWidth(150);
col3.setPreferredWidth(200);
col4.setPreferredWidth(150);
Connection conn;
Statement s;
ResultSet rs;
String cond = "";
String ename = jTextFieldNamaMajikan.getText();
String empType = jComboJenisMajikan.getSelectedItem().toString();
System.out.println("empType is :" +empType);
System.out.println("Name of Employee is :"+ename);
try{
conn = connection.getInstance().getConnection();
s = conn.createStatement();
//if(ename.length()==0){
//cond = "and employee_name ="+ename;
// System.out.println("Condition values :"+cond);
// }
String sql="select a.employer_name,a.employer_id,a.address1,b.description,c.description from d_workplace a,ems_ref_city b,ems_ref_state c,d_employer d where a.employer_id = d.emp_id and a.city_code = b.city_code and a.state_code = c.state_code and employer_name like '%"+ename+"%'";
// if(cond.length()!=0){
//sql += cond;
// }
s.execute(sql);
rs = s.getResultSet();
System.out.println("condition is :"+rs.toString());
if(ename.length() != 0){
if (rs != null)
while ( rs.next() )
{
((DefaultTableModel) jTable1.getModel()).insertRow(0, new Object[]{rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5)});
}
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,"An error occured: " + e);
}
}
The answer was given in reply 3 of the thread.