Link to home
Start Free TrialLog in
Avatar of killisrinivas
killisrinivas

asked on

JTable to Database

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??
Avatar of Ovi
Ovi

You must read a tutorial for your homework.
check JTable examples that come with jdk1.2 +
For heyhey_ : Nice to see you back.
hi ovi

did I miss anything ? :)
Yep, seems that the time is passing by and the areas of interrest among with it. Nice thing.
what's you current area of interest ?
Avatar of killisrinivas

ASKER

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
ASKER CERTIFIED SOLUTION
Avatar of sdussinger
sdussinger

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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();
  }

}
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.
You have forgot to graduate this question !!!!!!!!!! ... to someone ...