Efficiently identify modified values in JTable

Hi
I have a table with about 20 columns and 800 rows,
It was read only , now i have open this table for editing.
The user will update cells,and then click update database which will update those cells in database,
is there a efficient way to do this, or do i have to keep old values, and then read all table to compare it with old values to find out which are modified
Is there a row or cell listener which i can use to keep track of cells or rows which where modified,
This should be smart enough to differentiate between just a click and double click for the user to modify this value.
Any ideas or code would help
Ashish

One technique is to override the setValueAt( ) method of your TableModel and update the database instantly when the value changes. (Unless this is not the requirement)
Updates to a database record can take just a few seconds so this shouldn't hamper performance. However, you can just as well spawn a new thread and run the update from there.
ICE

Similar Messages

  • Reading values from JTable

    I have som problems reading the values from JTable. the user enters a number in the table, but some cells are empty. I want to store the values in an int array, and if the user has not filled a cell it is supposed to be set as zero. Now I cant seam to get it right.
    I get the error message: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: null
    It is for the code. Integer intObj = new Integer(str);[/u
    int[] tmp = new int[brettStorelse * brettStorelse];
    for (int i = 0; i < brettStorelse; i++) {
         for (int j = 0; j < brettStorelse;j++) {
              String k = String.valueOf(j+i);
              int l = Integer.parseInt(k);
              if (sudokuTabell.getValueAt(i, j) != null) {
                   String str = (String) sudokuTabell.getValueAt(i+1, j+1);
                   Integer intObj = new Integer(str);
                   tmp[l] = intObj.intValue();
                   System.out.println(tmp[l]);
              } else {
                   tmp[l] = 0;

    What are you doing to prevent the user from entering values in the table that are not parseable? Seems like you should be doing the below.
    int[] tmp = new int[brettStorelse * brettStorelse];
    for (int i = 0; i < brettStorelse; i++) {
         for (int j = 0; j < brettStorelse;j++) {
              String k = String.valueOf(j+i);
              int l = Integer.parseInt(k);
              if (sudokuTabell.getValueAt(i, j) != null) {
                   String str = (String) sudokuTabell.getValueAt(i+1, j+1);
                            try {
                                tmp[l] = Integer.parseInt (str);
                            catch (NumberFormatException e){
                                 tmp[l] = 0;
                   System.out.println(tmp[l]);
              } else {
                   tmp[l] = 0;
    }

  • How to enter the values in JTable in runtime

    how to enter the values in JTable in runtime

    Basically you need a vector of vectors or an array of arrays. Example (off the top of my head):
    With Arrays
    String[] cols = { "colone", "coltwo", "colthree", "colfour", "colfive" };
    String[] numbers = { "one", "two", "three", "four", "five" };
    String[] letters = { "A", "B", "C", "D", "E" };
    String[][] data = { numbers, letters };
    //make sure that the table has a scroll pane wrapped around it otherwise the header is not displayed
    JScrollPane scroll = new JScrollPane(new JTable(data, cols));
    With Vectors
    Vector cols = new Vector();
    cols.addElement("colone");
    cols.addElement("coltwo");
    cols.addElement("colthree");
    cols.addElement("colfour");
    cols.addElement("colfive");
    Vector numbers = new Vector();
    numbers.addElement("one");
    numbers.addElement("two");
    numbers.addElement("three");
    numbers.addElement("four");
    numbers.addElement("five");
    Vector letters = new Vector();
    numbers.addElement("A");
    numbers.addElement("B");
    numbers.addElement("C");
    numbers.addElement("E");
    numbers.addElement("F");
    Vector data = new Vector();
    data.addElement(numbers);
    data.addElement(letters);
    //make sure that the table has a scroll pane wrapped around it otherwise the header is not displayed
    JScrollPane scroll = new JScrollPane(new JTable(data, cols));The array or vector can be easily populated at runtime.
    Regards
    Riz

  • How i insert the values in JTable

    Hi,
    Iam new to the swings i have a problem placing the values in JTable while retriving the values from DataBase .Anybody please suggest me..
    i can retriving the values but how i place the vlaues..
    This is My code
    package com.teamone.healthcare;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.sql.DriverManager;
    import java.sql.Statement;
    import javax.swing.JButton;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.WindowConstants;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableModel;
    import com.mysql.jdbc.Connection;
    import com.mysql.jdbc.ResultSet;
    * This code was edited or generated using CloudGarden's Jigloo
    * SWT/Swing GUI Builder, which is free for non-commercial
    * use. If Jigloo is being used commercially (ie, by a corporation,
    * company or business for any purpose whatever) then you
    * should purchase a license for each developer using Jigloo.
    * Please visit www.cloudgarden.com for details.
    * Use of Jigloo implies acceptance of these licensing terms.
    * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
    * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
    * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
    public class ClientList extends javax.swing.JFrame {
         private static final long serialVersionUID = 1L;
         private JScrollPane list;
         private JButton view;
         private JButton close;
         private JTable jTable1;
         Connection con = null;
        Statement st = null;
        ResultSet rs = null;
         * Auto-generated main method to display this JFrame
         /*public static void main(String[] args) {
              ClientList inst = new ClientList();
              inst.setVisible(true);
         public ClientList() {
              super();
              initGUI();
              this.setVisible(true);
         private void initGUI() {
              try {
                        list.setBounds(161, 133, 371, 98);
                        list.getHorizontalScrollBar().setPreferredSize(new java.awt.Dimension(10, 59));
                   setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                   getContentPane().setLayout(null);
              try {
                    Class.forName("com.mysql.jdbc.Driver").newInstance();
                    con = (Connection) DriverManager.getConnection("jdbc:mysql:///healthcare","yenmad","yenmad");
                    st = con.createStatement();
                    rs = (ResultSet) st.executeQuery("SELECT User_id, Username, Citizen_ID, First_Name, Phone FROM register_users");
                    while(rs.next()) {
                      int Userid = rs.getInt(1);
                      String Username = rs.getString(2);
                      String ClientId = rs.getString(3);
                      String ClientName = rs.getString(4);
                      //String Last_Name = rs.getString(5);
                      String ContactNumber = rs.getString(5);
                      System.out.println(Userid + ", " + Username + ", " +ClientId  + "," + ClientName +","+ContactNumber);
                  } catch (Exception e) {
                       System.out.println("Exception: " + e.getMessage());
                        list = new JScrollPane();
                        getContentPane().add(list);
                        list.setBounds(0, 0, 644, 217);
                             TableModel jTable1Model = new DefaultTableModel(
                                  new String[][] { { "", "", "","", "" } },
                                  new String[]{ "UserId", "UserName", "ClientId", "ClientName", "ContactNumber"});
                             jTable1 = new JTable();
                             list.setViewportView(jTable1);
                             jTable1.setModel(jTable1Model);
                        close = new JButton();
                        getContentPane().add(close);
                        close.setText("Close");
                        close.setBounds(518, 231, 63, 28);
                        view = new JButton();
                        getContentPane().add(view);
                        view.setText("View");
                        view.setBounds(441, 231, 63, 28);
                        view.addActionListener(new ActionListener() {
                             public void actionPerformed(ActionEvent evt) {
                                  viewActionPerformed(evt);
                   pack();
                   this.setSize(652, 300);
              } catch (Exception e) {
                   e.printStackTrace();
         private void viewActionPerformed(ActionEvent evt) {
              System.out.println("view.actionPerformed, event=" + evt);
              new ViewClient();
    }

    can i display this table values in vertical .. if yes how can i do that.. please suggest me..
    this is the code iam using but it is displa in horizontally...
    package com.teamone.healthcare;
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.sql.DriverManager;
    import java.util.Vector;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.WindowConstants;
    import com.mysql.jdbc.Connection;
    import com.mysql.jdbc.ResultSet;
    import com.mysql.jdbc.ResultSetMetaData;
    import com.mysql.jdbc.Statement;
    public class ClientList extends javax.swing.JFrame {
         private static final long serialVersionUID = 1L;
         /*public static void main(String[] args) {
              ClientList inst = new ClientList();
              inst.setVisible(true);
         public ClientList() {
              super();
              initGUI();
              this.setVisible(true);
         private void initGUI() {
              try {
                   setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                   pack();
                   setSize(600, 500);
                   Vector columnNames = new Vector();
                Vector data = new Vector();
                try
                          this.setSize(500, 400);
                      //  Connect to the Database
                      Class.forName("com.mysql.jdbc.Driver");
                      Connection connection = (Connection) DriverManager.getConnection("jdbc:mysql:///healthcare","yenmad","yenmad" );
                      //  Read data from a table
                      String sql = "Select User_id, Username, Citizen_ID, First_Name, Last_Name, Phone from register_users";
                      Statement stmt = (Statement) connection.createStatement();
                      ResultSet rs = (ResultSet) stmt.executeQuery( sql );
                      ResultSetMetaData md = (ResultSetMetaData) rs.getMetaData();
                      int columns = md.getColumnCount();
                      //  Get column names
                      for (int i = 1; i <= columns; i++)
                       columnNames.addElement( md.getColumnName(i) );
                      //  Get row data
                      while (rs.next())
                            Vector row = new Vector(columns);
                            for (int i = 1; i <= columns; i++)
                                  row.addElement( rs.getObject(i) );
                            data.addElement( row );
                      rs.close();
                      stmt.close();
                catch(Exception e)
                      System.out.println( e );
                //  Create table with database data
                JTable table = new JTable(data, columnNames);
                JScrollPane scrollPane = new JScrollPane( table );
                getContentPane().add( scrollPane );
                JPanel buttonPanel = new JPanel();
                getContentPane().add( buttonPanel, BorderLayout.SOUTH );
                buttonPanel.setPreferredSize(new java.awt.Dimension(200, 66));
                        JButton View = new JButton();
                        buttonPanel.add(View);
                        View.setText("View");
                        View.setLayout(null);
                        View.addActionListener(new ActionListener() {
                             public void actionPerformed(ActionEvent evt) {
                                  ViewActionPerformed(evt);
                        JButton Close = new JButton();
                        buttonPanel.add(Close);
                        Close.setText("Close");
                        Close.addActionListener(new ActionListener() {
                             public void actionPerformed(ActionEvent evt) {
                                  CloseActionPerformed(evt);
                        } catch (Exception e) {
                   e.printStackTrace();
         private void CloseActionPerformed(ActionEvent evt) {
              System.out.println("Close.actionPerformed, event=" + evt);
              this.setVisible(false);
         private void ViewActionPerformed(ActionEvent evt) {
              System.out.println("View.actionPerformed, event=" + evt);
              new ViewClient();
    }

  • Why is OK disabled in the debugger's Modify Value dialog?

    Hi,
    For some reason OK disabled in the debugger's Modify Value dialog. Nothing that I have seen so far explains why this would happen. The variable stores an oracle.jbo.domain.Date, and the ADF source library was imported into the project.
    Ideas?
    James

    Hi Timo,
    You mentioned "tore" twice in your post, but I do know what that is. So, are you saying that if int or String was the type it would behave differently?
    James

  • Alter user identified by values

    I use the following method for connecting as different users for test purposes:
    - select the encrypted password from dba_users
    - temporarily change their password,
    - connect using a temporary password,
    - reset their original password using the encrypted value.
    The last step is achieved by the 'alter user identified by values ..' syntax.
    However, I have now found that if the user has a profile with password complexity verification, this always seems to fail.
    Appending the new 9.2 REPLACE <old_password> does not make any difference,
    and in any case that should not be needed if being done with alter any user privilege.
    Has anyone found a way around this ?

    The bad news is that on a 9.2 database I got the error:
    SQL> alter user a identified by values 'FD7C3F4E0D2D2A65' ;
    alter user a identified by values 'FD7C3F4E0D2D2A65'
    ERROR at line 1:
    ORA-28003: password verification for the specified password failed
    SQL>the good news is that on a 10.2 database it worked:
    SQL> alter user a identified by values 'FD7C3F4E0D2D2A65' ;
    User altered.
    SQL>

  • Modify Values Document Category List

    Hi All,
    Can you please explain how to modify values or add new ones to the Document Category list, that belongs to the manage contract documents Actions?
    I am working on OM > Blanket Sales Agreement >
    Thanks for your help
    Deneb

    What exactly do you need, just a list of categories applied on a document or something more? Here is a basic AttributeRequest for getting category info from document:
            AttributeRequest[] catAR = new AttributeRequest[]
              new AttributeRequest(Attributes.CATEGORIES, new AttributeRequest[]{
                new AttributeRequest(Attributes.CATEGORY_CLASS_OBJECT, new AttributeRequest[]{
                  new AttributeRequest(Attributes.DISPLAY_NAME, null)
                new AttributeRequest(Attributes.CUSTOM_ALL, null)
        Item file = fm.resolvePath(filePath, catAR);
        NamedValue[] categories = file.getRequestedAttributes();
        Item[] categoryInstances = (Item[])categories[0].getValue(); //index [0] is for Attributes.CATEGORIESthen you cycle through categoryInstances to get each category's display name.... Hope this helps, if you have any other questions - ask and I will try to give you the answer!
    Pedja

  • How to assign values to JTable using mysql database

    how to assign value to JTable using mysql...

    Search the forum. You use the values of the "ResultSet" to create a "DefaultTableModel" which you then add to the "JTable".
    I'll let you pick the search keywords to use, which I've suggested above. You can also throw in my userid if you want to specifically look for my solution.

  • 11g create user identified by values?

    In version 10g and under we could easily migrate users (including the password) from one database to another using:
    CREATE USER scott IDENTIFIED BY VALUES '{encrypted password}' ...blah, blah...
    What is the 11g equivalent of this command which would allow me to migrate users from one 11g database to another?
    Is datapump the ONLY option?

    Thanks to both, I did suspect spare4 was the encrypted password but what threw me off was the reference manual does not show the "BY VALUES" option in the "ALTER USER" syntax -- which actually what I needed. The users are already created and I want to synchronize the password with another db.
    ;)

  • Allowing user to modify/edit a JTable

    i'm new to java and i'm creating a JTable that allows a user to modify the data and the data will be stored in the database that i have created here is my code:
    import javax.swing.JTable;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.util.*;
    import javax.swing.event.*;
    import javax.swing.table.TableModel;
    public class SelectContacts extends JFrame implements TableModelListener {
    private boolean DEBUG = true;
    DataBase db = new DataBase();
    Connection connection = db.getConnection();
    public SelectContacts() {
    super("SelectContacts");
    DataBase db = new DataBase();
    Connection connection = db.getConnection();
    ArrayList contactsList =new ArrayList();
    String[] columnNames = {"Name",
    "Address",
    "Gender",
    "Email",
    "Contact",
    "Age"};
    String query;
    Statement statement;
    ResultSet rs;
    String personName="";
    String address="";
    String gender="";
    String email="";
    String contact="";
    String age="";
    Contacts s1;
    int i=0;
    query = "SELECT * FROM Contacts";
    try{
    statement = connection.createStatement();
    rs = statement.executeQuery(query);
    while (rs.next()){
         personName = rs.getString("Name");
    address = rs.getString("Address");
    gender = rs.getString("Gender");
    email = rs.getString("Email");
    contact = rs.getString("Contact");
    age = rs.getString("Age");
    s1= new Contacts(personName,address,gender,email,contact,age);
    contactsList.add(s1);
    i++;      
    statement.close();
    catch ( SQLException sqlex ) {
    sqlex.printStackTrace();
    Object[][] data = new Object[6];
    int count=0;
    while (count<i){
         s1 = (Contacts) contactsList.get(count);
         System.out.println("Name:" + s1.getName());
         System.out.println("Address:" + s1.getAddress());
         System.out.println("Gender:" + s1.getGender());
         System.out.println("Email:" + s1.getEmail());
         System.out.println("Contact No.:" + s1.getContact());
         System.out.println("Age:" + s1.getAge());
         data[count][0] = s1.getName();
         data[count][1] = s1.getAddress();
         data[count][2] = s1.getGender();
         data[count][3] = s1.getEmail();
                   data[count][4] = s1.getContact();
                   data[count][5] = s1.getAge();
    count++;
    final JTable table = new JTable(data, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.getModel().addTableModelListener(this);
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    highlighed
    public void tableChanged(TableModelEvent e) {
    int row = e.getFirstRow();
    int column = e.getColumn();
    TableModel model = (TableModel)e.getSource();
    String columnName = model.getColumnName(column);
    Object data = model.getValueAt(row, column);
    Statement statement;
    ResultSet rs;
         String insertString= "Insert into Contacts (Name, Address, Gender, Email, Contact, Age ) "+
              " VALUES ( '"+ data +"')";
              // Do something with the data...
    try{
    statement = connection.createStatement();
    statement.executeUpdate(insertString);
    statement.close();
    catch ( SQLException sqlex ) {
    sqlex.printStackTrace();
         System.out.println("You sucessfully modified! :)");          
    highlighted
    public static void main(String[] args) {
    SelectContacts frame = new SelectContacts();
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    //Whenever window gets the focus, let the
    //TextFieldDemo set the initial focus.
    public void windowActivated(WindowEvent e) {
    // demo.setFocus();
    frame.pack();
    frame.setVisible(true);
    i recieved error when i tried to edit 1 of the data "java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Number of query values and destination fields are not the same. i think the problem lies in the highlighted part. pls guide me thanks

    i think the problem lies in the highlighted part. pls guide me thanks What highlighted part? When you post code use the [code ]...[code ] tags. Read the "Formatting Help" link when you post a question for more information.
    I find it easier to use a PreparedStatement as it delimits a the parameters in your SQL statement for you. Here's a simple example, read the API for more information:
            private static void addData(Connection connection)
                throws Exception
                String sql =
                    "INSERT INTO Page " +
                         "(Name," +
                         "Title) " +
                     "VALUES " +
                PreparedStatement stmt = connection.prepareStatement(sql);
                stmt.setString( 1, "Name1" );
                stmt.setString( 2, "Title1" );
                stmt.executeUpdate();
                stmt.setString( 1, "Name2" );
                stmt.setString( 2, "Title2" );
                stmt.executeUpdate();
                stmt.close();

  • Get value from JTable

    I have created a 3-rows JTable and a JButton at a JFrame.
    The purpose of the JButton is to get all the value of the JTable and write to a text file.
    by the getValueAT method.
    User can press the save button any time after he/she modified the JTable.
    however, i discover a problem.
    problem:
    When user select a row, and modify it. and then press the save button.
    the getValueAt method still get the old value of the row and write to the text file unless user select another cell.
    in short, user has to select another cell after modified his/her target cell in order to let the modified to success.
    any experts can help?

    Hi,
    this is simply because the editing process is not finished at that time - if you want it to stop you should add a line of code to your ActionListener for your button:
    // assuming table is your JTable (subclass)
    if (table.isEditing()) { table.getCellEditor().stopCellEditing(); }
    this way the editing process is aborted and the particially edited contents of the cell are accepted.
    greetings Marsian

  • Touble getting cell values from jTable

    Hi everybody, I need some hepl to understand this problem.
    I have jtable and I�m trying to get the values from the cells (first in the jOption panel then to jLabel and to jTextFields).
    All cell values are shown perfectly in the JOptionPanel.
    But I can�t get any values to the jLabel from the first column(0) no matter what row I press from the firts column.
    It gives me this error
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Integer
         at taulukko3.FTaulukko3.jTable1_mouseClicked(FTaulukko3.java:163)Here is my code where I think the problem is:
    public void jTable1_mouseClicked(MouseEvent e) {
       JOptionPane.showMessageDialog(this,jTable1.getValueAt(jTable1.getSelectedRow(),jTable1.getSelectedColumn()));
          try{
          int valittusarake = jTable1.getSelectedColumn();
           String tulos= "";
           if (valittusarake == 0) {
             tulos = (String) jTable1.getValueAt(jTable1.getSelectedRow(),
                                                      jTable1.getSelectedColumn());
            jLabel1.setText(tulos);
           if (valittusarake == 1) {
             tulos = (String) jTable1.getValueAt(jTable1.getSelectedRow(),
                                                       jTable1.getSelectedColumn());
             jTextField1.setText(tulos);
           if (valittusarake == 2) {
             tulos = (String) jTable1.getValueAt(jTable1.getSelectedRow(),
                                                       jTable1.getSelectedColumn());
             jTextField2.setText(tulos);
    }

    Hi everybody
    I got it workin by making this change to my code:
          if (valittusarake == 0) {
             Object tulos1 = jTable1.getValueAt(jTable1.getSelectedRow(),jTable1.getSelectedColumn());
             jLabel1.setText(tulos1.toString());
          }

  • Getting Problem in retrieving values from JTable

    Hi Guys,
    Suppose i clicked in cell in a table to edit it and done some entry in it and without leaving that cell ( means focus is on that cell only) i clicked one button.
    button prints table data on console.
    now problem is the value in focused cell is coming as null or wht i previously return.
    that means unless i m not leaving a cell the Jtable is not taking that value.
    how could i overcome this problem
    thanks in advance

    Use this:table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);The editor will be closed as soon as the table loses focus.

  • Hiding a cell value in Jtable

    Is it possible to hide a cell value in a JTable?. The value should be present in the JTable but just hidden
    tnx

    Yes, there are a few ways to do this. I'm sure there are others, but here are 2 quick ways:
    1. When the cell value (Object ) is being rendered, it's toString() method is called. Create a subclass of whatever Object you are using in cells and override the toString() method.
    2. Create you own cell renderer and then you can renderer the contents of a cell however you wish.
    Regards,
    Muel.

  • Need Suggestion for Modifying values of dashboard

    Hi ALL,
    I have created a dashboard that has four tables all have drill down features. These all table have a common column "Market Worth".
    I have created a prompt that has two column , Bank Name and Base currency.
    When a user select a bank name its corresponding base currency will be shown.
    Could it be possible that as soon as the user select a bank name then the data in the "Market Worth" get converted into corresponding value based on base currency ?
    One thing more, can we modify the column heading of table dynamically?
    Thanks
    Ashok

    There will not be any updates /deletes on the table.
    I have created a partitioned table with same struture and i am inserting the records from my original table to this partitioned table where i will maintain data for 6 months.
    After loading the data from original table to archived table i will truncating the original table.
    If my original table is partitioned then what about the restoring of the data??? how will restore the data of last month???

Maybe you are looking for