Solved

Using JTable with Database

Posted on 2004-08-16
13
702 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 6
13 Comments
 
LVL 35

Expert Comment

by:girionis
ID: 11810320
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 17

Author Comment

by:aiklamha
ID: 11817761
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 35

Expert Comment

by:girionis
ID: 11817894
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
ID: 11818686
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
ID: 11818760
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
 
LVL 17

Author Comment

by:aiklamha
ID: 11820101
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
ID: 11820165
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
ID: 11827626
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
ID: 11827813
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
ID: 11827933
> 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
ID: 11828067
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
ID: 11828154
Not sure, you can always try.
0

Featured Post

The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
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…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

707 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