[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Using JTable with Database

Posted on 2004-08-16
13
Medium Priority
?
710 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
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 150 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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

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…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses

656 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