Solved

Using JTable with Database

Posted on 2004-08-16
13
682 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
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 4

Expert Comment

by:JK2429
ID: 11811021
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
Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

 
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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
topping2 challenge 13 89
maven project error 5 54
Should localization be done inside spring controller 5 25
Java exception bubble up 2 17
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

815 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