Solved

Using JTable with Database

Posted on 2004-08-16
13
660 Views
Last Modified: 2012-06-21
I want to see an example of how to build a AbstractTableModel to get data from the Database...
let me rephrase the question..
I want to be able to display data from a database table in a JTable...

can some1 give me a simple example..?
0
Comment
Question by:aiklamha
  • 6
  • 6
13 Comments
 
LVL 35

Expert Comment

by:girionis
Comment Utility
For JTable examples look here: http://javaalmanac.com/cgi-bin/search/find.pl?words=jtable

For database tutorials look here: http://java.sun.com/docs/books/tutorial/jdbc/basics/

If you follow the examples you can combine them both :)
0
 
LVL 4

Expert Comment

by:JK2429
Comment Utility
0
 
LVL 17

Author Comment

by:aiklamha
Comment Utility
Thanx for your great help.. i saw all the examples all of them are getting Data directly into the JTable.. I want to create a Table Model to read the data from Database and then set that Table Model on the Jtable...Pardon me.. i am very new to this...
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
Have you got some sample code that reads the data from the database? If yes then we can guide you step-by-step how you could get this data into a JTable.
0
 
LVL 17

Author Comment

by:aiklamha
Comment Utility
This is what i have done so far...
This code reads the data from Resultset into a vector and then i m using DTM ...
My Questions are
1.    Should i use my own TableModel or should it be left as is...
2.    What should i do to reflect the editing, done in the JTable, to the database?


import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.sql.*;
import java.util.*;
public class DBDisplayer extends JFrame
{
    JTable mytable;
    Connection con;    
    JScrollPane sp;
    Container c;
    Statement st;
    ResultSet rs;
    ResultSetMetaData meta;
    Vector columnNames=new Vector();
    Vector data=new Vector();            //should be vector of vectors
    static
      {
            try
            {
                  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            }
            catch(Exception e)
            {
                  System.out.println("Error " + e);
            }
            
      }
    public DBDisplayer()
    {
      try
      {
            mytable = new JTable();
              sp = new JScrollPane(mytable);
      
            //Getting Data From database
            con = DriverManager.getConnection("jdbc:odbc:test");
            st = con.createStatement();
            rs = st.executeQuery("Select * from Test");
            columnNames.addElement("TestID");
              columnNames.addElement("TestName");
            Vector tempVector;
      
            while(rs.next())
            {
                  System.out.println("Inside while");
                  tempVector = new Vector();
                  tempVector.addElement(rs.getString("TestID"));
                  tempVector.addElement(rs.getString("TestName"));
                  data.addElement(tempVector);
                  tempVector=null;
            }
            System.out.println("outside while");
            mytable.setModel(new DefaultTableModel(data,columnNames));

/////////Install Cell Editor//////////////////////
            int vColIndex = 0;
            TableColumn col = mytable.getColumnModel().getColumn(vColIndex);
            MyTableCellEditor myeditor = new MyTableCellEditor();
            col.setCellEditor(myeditor);
///////////////////////////////////



              c = getContentPane();
              c.add(sp);
//              c.add(mytable);
            setSize(300,400);
              setVisible(true);
      }catch(Exception e){ e.printStackTrace();}
    }  
    public static void main(String[] s)
    {
        DBDisplayer d = new DBDisplayer();
    }
}


    // Install the custom editor on the first column
   
class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor {
        // This is the component that will handle the editing of the cell value
        JComponent component = new JComboBox(new String[]{"Hello","Hi"});
      public MyTableCellEditor()
       {
            ((JComboBox)component).setEditable(true);
      }  
        // This method is called when a cell value is edited by the user.
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int rowIndex, int vColIndex) {
            // 'value' is value contained in the cell located at (rowIndex, vColIndex)
   
            if (isSelected) {
                // cell (and perhaps other cells) are selected
            }
   
            // Configure the component with the specified value
            ((JComboBox)component).setSelectedItem((String)value);
   
            // Return the configured component
            return component;
        }
   
        // This method is called when editing is completed.
        // It must return the new value to be stored in the cell.
        public Object getCellEditorValue() {
            System.out.println("Completed");
            return ((JComboBox)component).getSelectedItem();
        }
    }
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
1) Leave it as it is, a DefaultTableModel is enough for most of the cases.

2) Load all data into a vector and then insert all changes in the database. If "model" is your table model you could do something like:

Vector data = model.getDataVector();
for (int i=0; i<data.size(); i++)
{
    Vector row = (Vector) data.elementAt(i);
    // prepare statement
    // set field of ps to the first value of row.
    // set field of ps to the second value of row
    // ...
}
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 17

Author Comment

by:aiklamha
Comment Utility
Wudn't it be slow to load all of the data on even a minor change?
Like.. if user has just edited one cell in JTable.. should i load ALL the data and put it in Database everytime?
wouldn't it be efficient to just get the updated value and update that very record? If yes! can u give any hint on how to do it?
0
 
LVL 35

Accepted Solution

by:
girionis earned 50 total points
Comment Utility
No you shouldn't. My example show how you can insert the data if multiple rows and cells are changed. If you just updated a cell and you want to reflect the change in the database you could simply do (assuming it is a String):

String value = (String) table.getModel().getValueAt(rowIndex, mColIndex);

and then the db code should be the same with the only difference that you don't have to iterate over all rows.
0
 
LVL 17

Author Comment

by:aiklamha
Comment Utility
N how to notify Table about the changes in database table? keeping in mind that a table can be edited by several users at one time...
0
 
LVL 17

Author Comment

by:aiklamha
Comment Utility
One more question.. I m using a custom Cell Editor.. i have designed my own  Jcomponent for this pupose which contains 1 JTextField and two JButtons... When i click on any cell.. only the portion which can be shown in Cell's width and height is visible... how to fix that?
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
> N how to notify Table about the changes in database table?

Just read the new data from the database and add it to the table model.

> When i click on any cell.. only the portion which can be shown in Cell's width and height is visible... how to fix that?

This might help: http://forum.java.sun.com/thread.jsp?forum=57&thread=123587&tstart=0&trange=15
0
 
LVL 17

Author Comment

by:aiklamha
Comment Utility
The thread u supplied the link of is just telling how to resize the columns according to the data present ..
Can we apply the same logic while using CellEditors? Are CellEditors are just like contents to the TableCell?
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
Not sure, you can always try.
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now