Solved

JTable to Database

Posted on 2001-09-02
11
497 Views
Last Modified: 2013-11-23
iam using JTable to enter data into database. how can i enter data into jtable(editable) and later retrieve data from jtable cells to enter into database? can anybody plz help me out with some code??
0
Comment
Question by:killisrinivas
[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
11 Comments
 
LVL 9

Expert Comment

by:Ovi
ID: 6450101
You must read a tutorial for your homework.
0
 
LVL 16

Expert Comment

by:heyhey_
ID: 6450255
check JTable examples that come with jdk1.2 +
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6450283
For heyhey_ : Nice to see you back.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 16

Expert Comment

by:heyhey_
ID: 6450298
hi ovi

did I miss anything ? :)
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6450416
Yep, seems that the time is passing by and the areas of interrest among with it. Nice thing.
0
 
LVL 16

Expert Comment

by:heyhey_
ID: 6450723
what's you current area of interest ?
0
 

Author Comment

by:killisrinivas
ID: 6451240
i have been thru the tutorial and jdk1.2+ exmaples. im still getting problem. that's the reason i've posed my q here at EE. lemme drop my code here.

My JTable starts with only one row. how to increase the rows after each time i press ENTER in the last column. i have coded the program as following. plzzz help me !!!!

import java.sql.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Vector;
import javax.swing.table.*;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;


public class TableDemo extends JFrame
 {
   private boolean ALLOW_ROW_SELECTION = false;
   private boolean ALLOW_COLUMN_SELECTION = true;
   final JTable table;

   public TableDemo()
    {
      MyTableModel model = new MyTableModel();
      table = new JTable(model);
      table.setColumnSelectionAllowed(true);
      table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

      if(ALLOW_ROW_SELECTION)
       {
         ListSelectionModel select = table.getSelectionModel();
         select.addListSelectionListener(new ListSelectionListener()
          {
            public void valueChanged(ListSelectionEvent lse)
             {
               if(lse.getValueIsAdjusting()) return;

               ListSelectionModel lsm = (ListSelectionModel)lse.getSource();
               int selectedRow = lsm.getMinSelectionIndex();
             }
          });
       }
      else
       { table.setRowSelectionAllowed(false); }


      if(ALLOW_COLUMN_SELECTION)
       {
         if(ALLOW_ROW_SELECTION)
          {
            table.setCellSelectionEnabled(true);
          }
         table.setColumnSelectionAllowed(true);
         ListSelectionModel select = table.getColumnModel().getSelectionModel();
         select.addListSelectionListener(new ListSelectionListener()
          {
            public void valueChanged(ListSelectionEvent lse)
             {
               if(lse.getValueIsAdjusting()) return;

               ListSelectionModel lsm = (ListSelectionModel)lse.getSource();
               int selectedCol = lsm.getMinSelectionIndex();
             }
          });
       }

//      table.setPreferredScrollableViewportSize(new Dimension(500,50));
      JScrollPane jsp = new JScrollPane(table);
      getContentPane().add(jsp);
      addWindowListener(new WindowAdapter()
       {
         public void windowClosing(WindowEvent we)
          { System.exit(0); }
       });

      setSize(500,300);
      setVisible(true);
    }

   public static void main(String args[])
    { new TableDemo(); }
 }

--------------

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Vector;
import javax.swing.table.*;

public class MyTableModel extends AbstractTableModel
 {

   String[] colNames = {"Sl. No.", "Product", "Quantity", "Price", "Discount", "Amount"};
   String[][] rows = {{"", "", "", "", "", ""}};

   public int getColumnCount()
    { return colNames.length; }

   public int getRowCount()
    { return rows.length; }

   public String getColumnName(int col)
    { return (String)colNames[col]; }

   public Object getValueAt(int row, int col)
    { return rows[row][col]; }

   public boolean isCellEditable(int row, int col)
    {  return true;  }

   public void setValueAt(Object value, int row, int col)
    {
      rows[row][col] = value.toString();
      fireTableCellUpdated(row, col);
    }
 }

------------------------


regards,
killi
0
 
LVL 4

Accepted Solution

by:
sdussinger earned 200 total points
ID: 6452228
I've modified your original code to handle the addition of a new blank row:

TableDemo.java:

import java.sql.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Vector;
import javax.swing.table.*;
import javax.swing.event.*;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

class MyTable extends JTable
{

    public MyTable (TableModel model)
    {
        super (model);
    }

    public void processEvent (java.awt.AWTEvent e)
    {
        // Handle only key press events...
        if (e instanceof KeyEvent && e.getID () == Event.KEY_PRESS)
        {
            KeyEvent ke = (KeyEvent) e;
            MyTableModel mtm = (MyTableModel) getModel ();

            // This one handles a DOWN arrow pressed while in the last row.
            if (ke.getKeyCode () == KeyEvent.VK_DOWN && getSelectedRow () == getRowCount () - 1 )
            {
                // Add a blank row to the table and force it to redraw.
                mtm.addBlankRow ();
                invalidate ();
            }
            // Handle an ENTER key press....
            else if (ke.getKeyCode () == KeyEvent.VK_ENTER)
            {
                ListSelectionModel rsm = getSelectionModel ();
                ListSelectionModel csm = getColumnModel ().getSelectionModel ();
                int row = rsm.getMinSelectionIndex ();
                int col = csm.getMinSelectionIndex ();

                // If we're at the last column in the last row...
                if (getSelectedRow () == getRowCount () - 1 &&
                getSelectedColumn () == getColumnCount () - 1)
                {
                    // Add a new blank row and force a redraw...
                    mtm.addBlankRow ();
                    invalidate ();

                    csm.setSelectionInterval (0,0);
                }
                // Otherwise we want to just force a row-major traversal.
                // Comment this entire else block out if you
                // want to keep the column-major traversal intact...
                else
                {
                    // Check to see if we're at the last column...
                    if (col == getColumnCount () - 1)
                    {
                        // Yes, reset the selection to the first element in
                        // the next row.
                        csm.setSelectionInterval (0,0);
                        rsm.setSelectionInterval (row+1,row+1);

                        // Force a return, so that the superclass doesn't try
                        // to do any subsequent processing.
                        return;
                    }
                    else
                    {
                        // We're somewhere other than the last column. Move
                        // the selection to the next column in the current row.
                        csm.setSelectionInterval (col+1,col+1);

                        // Force a return, so that the superclass doesn't try
                        // to do any subsequent processing.
                        return;
                    }
                }
            }
        }

        super.processEvent (e);
    }
}

public class TableDemo extends JFrame
{
    private boolean ALLOW_ROW_SELECTION = false;
    private boolean ALLOW_COLUMN_SELECTION = false;
    final JTable table;

    public TableDemo()
    {
        // Create a new model.
        MyTableModel model = new MyTableModel();

        // Since the model is dynamic, we have to initialize it to get the
        // first blank row to display and edit.
        model.init ();

        table = new MyTable(model);
        table.setColumnSelectionAllowed(true);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        if(ALLOW_ROW_SELECTION)
        {
            ListSelectionModel select = table.getSelectionModel();
            select.addListSelectionListener(new ListSelectionListener()
            {
                public void valueChanged(ListSelectionEvent lse)
                {
                    if(lse.getValueIsAdjusting()) return;

                    ListSelectionModel lsm = (ListSelectionModel)lse.getSource();
                    int selectedRow = lsm.getMinSelectionIndex();
                }
            });
        }
        else
        {
            table.setRowSelectionAllowed(false);
        }


        if(ALLOW_COLUMN_SELECTION)
        {
            if(ALLOW_ROW_SELECTION)
            {
                table.setCellSelectionEnabled(true);
            }
            table.setColumnSelectionAllowed(true);
            ListSelectionModel select = table.getColumnModel().getSelectionModel();
            select.addListSelectionListener(new ListSelectionListener()
            {
                public void valueChanged(ListSelectionEvent lse)
                {
                    if(lse.getValueIsAdjusting()) return;

                    ListSelectionModel lsm = (ListSelectionModel)lse.getSource();
                    int selectedCol = lsm.getMinSelectionIndex();
                }
            });
        }
        else
        {
            table.setColumnSelectionAllowed (false);
        }

        //      table.setPreferredScrollableViewportSize(new Dimension(500,50));
        JScrollPane jsp = new JScrollPane(table);
        getContentPane().add(jsp);
        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent we)
            { System.exit(0); }
        });


        setSize(500,300);
        setVisible(true);
    }

    public static void main(String args[])
    {
        new TableDemo();
    }
}



MyTableModel.java:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Vector;
import javax.swing.table.*;

public class MyTableModel extends AbstractTableModel
{

    String[] colNames = {"Sl. No.", "Product", "Quantity", "Price", "Discount", "Amount"};
    String [] blankRow = {"","","","","",""};

    // Dynamic storage for the rows.
    Vector rows = new Vector ();

    // Initialize the rows vector by adding the first blank row.
    public void init ()
    {
        addBlankRow ();
    }

    // Add a blank row to the vector.
    public void addBlankRow ()
    {
        rows.add ( new String [] {"","","","","",""} );
    }

    public int getColumnCount()
    { return colNames.length; }

    public int getRowCount()
    { return rows.size(); }

    public String getColumnName(int col)
    { return (String)colNames[col]; }

    public Object getValueAt(int row, int col)
    {
        String [] rowElems = (String [])rows.elementAt (row);
        return (rowElems[col]);
    }

    public boolean isCellEditable(int row, int col)
    {  return true;  }

    public void setValueAt(Object value, int row, int col)
    {
        String [] rowElems = (String []) rows.elementAt (row);
        rowElems[col] = value.toString();
        fireTableCellUpdated(row, col);
    }
}

The code also handles the addition of a new row when the DOWN arrow key is pressed in the last row of the table, and changes the traversal from column-major to row-major. If you don't want the row-major traversal stuff, just comment the code in the processEvent method out...


HTH

--Steve
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6452234
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

public class SimpleTable extends JFrame {
  private SmartTable table;
  private Actions actions;

  public SimpleTable() { init(); }

  private void init() {
    getContentPane().setLayout(new BorderLayout());
    setSize(600, 300);
    setLocation(300, 100);
    table = new SmartTable();
    actions = new Actions();
    getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
    getContentPane().add(actions, BorderLayout.SOUTH);
    setVisible(true);
  }

  class Actions extends JPanel {
    JButton add = new JButton("Add");
    JButton remove = new JButton("Remove");
    JButton dump = new JButton("Dump content to console");
    public Actions() {
      setLayout(new FlowLayout());
      setListeners();
      add(add);
      add(remove);
      add(dump);
    }

    public DBObject createDBObject() {
      DBObject dbo = new DBObject();
      int curent = SimpleTable.this.table.getRowCount();
      dbo.f1 = "DBO " + curent + " field 1";dbo.f2 = "DBO " + curent + " field 2";
      dbo.f3 = "DBO " + curent + " field 3";dbo.f4 = "DBO " + curent + " field 4";
      dbo.f5 = "DBO " + curent + " field 5";dbo.f6 = "DBO " + curent + " field 6";
      dbo.f7 = "DBO " + curent + " field 7";dbo.f8 = "DBO " + curent + " field 8";
      return(dbo);
    }

    protected void setListeners() {
      add.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
          SimpleTable.this.table.addDBObject(createDBObject());
        }
      });
      remove.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
          int selected = SimpleTable.this.table.getSelectedRow();
          SimpleTable.this.table.removeDBObjectAt(selected);
        }
      });
      dump.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
          Vector objs = SimpleTable.this.table.getDBObjects();
          for(int i = 0; i < objs.size(); i++) {
            DBObject o = (DBObject)objs.elementAt(i);
            System.out.println("DBObject " + i + ": " + o.f1 + ", " + o.f2 + ", " + o.f3 +
            ", " + o.f4 + ", " + o.f5 + ", " + o.f6 + ", " + o.f7 + ", " + o.f8);
          }
        }
      });
    }
  }

  class SmartTable extends JTable {
    SmartTableModel model;

    public SmartTable() {
      model = new SmartTableModel();
      createColumns();
      setModel(model);
      setForeground(Color.red);
      setBackground(new Color(255, 239, 185));
      setGridColor(Color.orange);
      setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    protected void createColumns() {
      for(int i = 0; i<model.getColumnCount(); i++) {
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setHorizontalAlignment(model.cols[i].alignment);
        TableColumn column = new TableColumn(i, model.cols[i].width, renderer, null);
        addColumn(column);
      }
    }

    public void addDBObject(DBObject object) { model.addDBObject(object);}
    public void addDBObjects(Vector objects) { model.addData(objects);}
    public void removeDBObjectAt(int idx) { model.removeDBObjectAt(idx);}
    public DBObject getDBObject(int row) { return(model.getDBObject(row)); }
    public Vector getDBObjects() { return(model.getDBObjects()); }
  }

  class SmartTableModel extends AbstractTableModel {
    protected ColumnDescriptor cols[] =  {
      new ColumnDescriptor("Field1", 40, JLabel.LEFT),
      new ColumnDescriptor("Field2", 50, JLabel.LEFT),
      new ColumnDescriptor("Field3", 100, JLabel.LEFT),
      new ColumnDescriptor("Field4", 60, JLabel.LEFT),
      new ColumnDescriptor("Field5", 50, JLabel.LEFT),
      new ColumnDescriptor("Field6", 40, JLabel.LEFT),
      new ColumnDescriptor("Field7", 40, JLabel.LEFT),
      new ColumnDescriptor("Field8", 40, JLabel.LEFT),
    };
    protected Vector dbObjects;

    public SmartTableModel() {
      dbObjects = new Vector();
    }

    public void addData(Vector v) {
      dbObjects.removeAllElements();
      for(int i = 0; i<v.size(); i++) {
        dbObjects.addElement((DBObject) v.elementAt(i));
      }
      updateObjects();
    }

    public void addDBObject(DBObject dbo) {
      dbObjects.addElement(dbo);
      updateObjects();
    }
    public void removeDBObjectAt(int idx) {
      dbObjects.removeElementAt(idx);
      updateObjects();
    }

    public DBObject getDBObject(int row) {
      return((DBObject)dbObjects.elementAt(row));
    }

    public Vector getDBObjects() {
      return(dbObjects);
    }

    protected void updateObjects() {
      fireTableDataChanged();
    }

    public int getColumnCount() { return(cols.length); }
    public int getRowCount() { return(dbObjects.size()); }
    public String getColumnName(int c) { return(cols[c].name); }
    public boolean isCellEditable(int row, int col) { return(true); }

    public Object getValueAt(int row, int col) {
      if(getRowCount() <= 0)
        return "";
      if(row<0||row>=getRowCount())
        return "";
      DBObject dbo = (DBObject) dbObjects.elementAt(row);
      switch(col) {
        case 0: return dbo.f1;
        case 1: return dbo.f2;
        case 2: return dbo.f3;
        case 3: return dbo.f4;
        case 4: return dbo.f5;
        case 5: return dbo.f6;
        case 6: return dbo.f7;
        case 7: return dbo.f8;
      }
      return "";
    }

  }

  class ColumnDescriptor {
    public String name;
    public int width;
    public int alignment;

    public ColumnDescriptor(String n, int w, int a) {
      name = n;
      width = w;
      alignment = a;
    }
  }

  class DBObject {
    public String f1;
    public String f2;
    public String f3;
    public String f4;
    public String f5;
    public String f6;
    public String f7;
    public String f8;
  }

  public static void main(String[] args) {
    SimpleTable t = new SimpleTable();
  }

}
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6452238
Add, remove, dump content. Basically the example is ready to use in this structure, all you have to do is to implement the logic for retrieving the data from the database. In this example is only simulated via Add button. Anyway take a look to the table methods in the example, you will find there add one element , add many elements, get one element, get all elements, remove the curent selected element.

Cheers.
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6604769
You have forgot to graduate this question !!!!!!!!!! ... to someone ...
0

Featured Post

Industry Leaders: 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!

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…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

622 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