Using JTable with Database

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..?
LVL 17
Muhammad KhanManager, ITAsked:
Who is Participating?
 
girionisConnect With a Mentor Commented:
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
 
girionisCommented:
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
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
Muhammad KhanManager, ITAuthor Commented:
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
 
girionisCommented:
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
 
Muhammad KhanManager, ITAuthor Commented:
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
 
girionisCommented:
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
 
Muhammad KhanManager, ITAuthor Commented:
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
 
Muhammad KhanManager, ITAuthor Commented:
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
 
Muhammad KhanManager, ITAuthor Commented:
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
 
girionisCommented:
> 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
 
Muhammad KhanManager, ITAuthor Commented:
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
 
girionisCommented:
Not sure, you can always try.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.