Updating JTable From Database

Hi,
I am new to Swing and I was wondering if anyone could help me with the following problem.
I have a tablemodel which extends AbstractTableModel which is used to create my JTable. The data to display in the table is got from a SELECT statement from the database, this works fine.
The problem is that I have a rollback button which rollbacks any data changed in the database. I then have to do another SELECT statement from the database to populate the table again.
Is there anyway to do this other than calling the Select function?
Any Help or Ideas would be greatly appreciated.
Thanks in advance
Frank

Thanks for replying ceccs,
I did try this by creating a backup vector of the database table. But everytime I changed the data in the Jtable this changed the backup one.
I haven't got a clue as to why this is happening

Similar Messages

  • Update Model from database does not update Nullable Property -- Possible bug?

    Hi,
    I don't know if this is the correct forum.
    When updating Model from database seems does not update the entity nullable property.
    and it will not update the Default Value from the Backend (MSSQL) also.
    I am using VS2008 SP1 3.5EF, XP64Bit Machine.
    Thanks
    vb.net GUI

    maybe related..
    today.. i changed the PK size.. from char(10) to char(36)
    got many problems.. easy to fix...
    but some query stop working:
    Table1Record.Table2Reference.Load(); //i'm trying to load table2 from table1..
    throw this error: A relationship multiplicity constraint violation occurred: An EntityReference expected at least one related object, but the query returned no related objects from the data store.
    i get this error only when PK is greater than char(10)...
    with SQL profiler.. i saw that PK was truncated to char(10) :
    exec sp_executesql N'SELECT [... some fields...]
    FROM  [dbo].[Table1] AS [Extent1]
    INNER JOIN [dbo].[Table2] AS [Extent2] ON [Extent1].[NoTable2] = [Extent2].[NoTable2]
    WHERE [Extent1].[NoTable1] = @EntityKeyValue1',N'@EntityKeyValue1 char(10)',@EntityKeyValue1='a2164b14-e'
    (NoTable1 is the PK changed from char(10) to char(36))
    i'm working with VS.NET 2008
    so, i looked at Model1.Edmx... in notepad
    CSDL was not changed when i did the "Update Model from Database" !!!
    here is SSDL part:
            <EntityType Name="Table1">
              <Key>
                <PropertyRef Name="NoTable1" />
              </Key>
              <Property Name="NoTable1" Type="char" Nullable="false" MaxLength="36" />
    here is CSDL part:
            <EntityType Name="Table1">
              <Key>
                <PropertyRef Name="NoTable1" />
              </Key>
              <Property Name="NoTable1" Type="String" Nullable="false" MaxLength="10" Unicode="false" FixedLength="true" />
    Cool.. i found the prob.... but why ? and how to correct this ? manually change Model1.Edmx in notepad ??
    why the maxlength property is readonly in Model Browser pane ??
    what about VS.NET 2010 ?! same prob ??
    is it a bug or by design ?
    I hope this can help someone.. I spent a few hours on this prob
    Patrick

  • Update Jtable from access database

    as the title suggests help me guys... till now i have a database and some contents in it.. when the application starts the table is filled with contents of the database.. now whenever i add or remove a row in the databse i want to show it in the table... i have a Vector called dbData with the present contents of the database.. i want to update jtable with contents of dbData.... how to do it??

    the best things i can see to do is
    JTable table = new Jtable(.....); // this was ur table before;
    deleteRow(table); // you deleted the row
    // now you have a vector containing all the data for the rows;
    // but you need a vector containing the columns for the rows too
    //so now you do
    table = new JTable(dbData,columnnames);
    repaint();dbData must be a vector of vectors;
    dbData.elementAt(1) return a vector with all the data for row one
    so dbData.elementAt(1).elementAt(1) will be the data for row 1 column 1
    // dbData will be the data still remaining in the table
    or instead of the above you could use a nested for loop and set each element one at a time
    Object temp;
    int numberofRows = dbData.elementCount();
    int numberofColumns = db.elementAt(0).elementCount();
    for(int row = 0; row < numberofColumns;row++)
    for( int column = 0; column < numberofRows; column++)
      temp = dbData.elementAt(row).elementAt(column);
      table.setValueAt(temp,row,column);
    }

  • Update ztable from database table directly

    hi all,
    can u tell me the possible ways to update a ztable from database table directly.
    i mean is there anyway to update ztable whenever entry is created in database table .
    i dont want to update using insert,modify statements.
    points will be rewarded to all hlpful answers.

    A slightly dirty solution:
    Use SAP functions for reading from CDHEADER and CDPOS tables [with enough filters such that you extract minimum records possible] to read changes to MARA table fields since last run of your program. Use this information to update your ZTABLE. I would recommend having a table maintainance generator on ZTABLE. The actual update should be by a BDC by calling transaction SM30 for ZTABLE maintainance. Now the program may be set up as a batch job running 1ce an hour. You get updates to the extent of 1 hour latency.
    Alternatively, you may look if an opportunistic BADI / user Exit is there alongside MM01/02 transactions - assuming the latter are the only ones updating MARA. In this BADI you may write the code to update ZTABLE- again, look to do it by BDC call transaction sm30 to maintain ZTable. To lighten up the code -load on BADI you may simply raise a custom event and move on. You will configure a job that runs your program when that particular event is raised. This will need the 'burden' of figuring out the changes, though.
    An elegant way would be to fire a MATMAS fIDOC for every change to Material, capture that and turn back the changes to ZTABLE. This will facilitate the delta load.

  • How to get data in jtable from database

    i m working on core java application i want to use jtable to show records to user. jtable will get records from mssql database. how to do this.. i m new so plz tell me briefly..with coding...
    thanks

    i have use this link:
    import java.sql.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    * This class takes a JDBC ResultSet object and implements the TableModel
    * interface in terms of it so that a Swing JTable component can display the
    * contents of the ResultSet. Note that it requires a scrollable JDBC 2.0
    * ResultSet. Also note that it provides read-only access to the results
    public class ResultSetTableModel implements TableModel {
    ResultSet results; // The ResultSet to interpret
    ResultSetMetaData metadata; // Additional information about the results
    int numcols, numrows; // How many rows and columns in the table
    * This constructor creates a TableModel from a ResultSet. It is package
    * private because it is only intended to be used by
    * ResultSetTableModelFactory, which is what you should use to obtain a
    * ResultSetTableModel
    ResultSetTableModel(ResultSet results) throws SQLException {
         this.results = results; // Save the results
         metadata = results.getMetaData(); // Get metadata on them
         numcols = metadata.getColumnCount(); // How many columns?
         results.last(); // Move to last row
         numrows = results.getRow(); // How many rows?
    * Call this when done with the table model. It closes the ResultSet and
    * the Statement object used to create it.
    public void close() {
         try { results.getStatement().close(); }
         catch(SQLException e) {};
    /** Automatically close when we're garbage collected */
    protected void finalize() { close(); }
    // These two TableModel methods return the size of the table
    public int getColumnCount() { return numcols; }
    public int getRowCount() { return numrows; }
    // This TableModel method returns columns names from the ResultSetMetaData
    public String getColumnName(int column) {
         try {
         return metadata.getColumnLabel(column+1);
         } catch (SQLException e) { return e.toString(); }
    // This TableModel method specifies the data type for each column.
    // We could map SQL types to Java types, but for this example, we'll just
    // convert all the returned data to strings.
    public Class getColumnClass(int column) { return String.class; }
    * This is the key method of TableModel: it returns the value at each cell
    * of the table. We use strings in this case. If anything goes wrong, we
    * return the exception as a string, so it will be displayed in the table.
    * Note that SQL row and column numbers start at 1, but TableModel column
    * numbers start at 0.
    public Object getValueAt(int row, int column) {
         try {
         results.absolute(row+1); // Go to the specified row
         Object o = results.getObject(column+1); // Get value of the column
         if (o == null) return null;
         else return o.toString(); // Convert it to a string
         } catch (SQLException e) { return e.toString(); }
    // Our table isn't editable
    public boolean isCellEditable(int row, int column) { return false; }
    // Since its not editable, we don't need to implement these methods
    public void setValueAt(Object value, int row, int column) {}
    public void addTableModelListener(TableModelListener l) {}
    public void removeTableModelListener(TableModelListener l) {}
    the table is showing column name from database but not showing the data in row now what to do

  • Updating JTable From List

    hi all
    i am having trouble updating a jtable from a list.
    the table is declared as follows
    //TableTracks.java
    String[] columnNames = {"Track Number",
      "Mute",
      "File/Track Name",
      "Number of Loops",
    Object[][] data = {
    {"1", "0", "", "1" , },
    {"2", "0", "", "1" , },
    {"3", "0", "", "1" , },
    {"4", "0", "", "1" , },
    {"5", "0", "", "1" , },
    {"6", "0", "", "1" , },
    {"7", "0", "", "1" , },
    {"8", "0", "", "1" , },
         final JTable table = new JTable(data, columnNames);I would like to select a value in a List by using the arrow keys, then when pressing enter key the selected List value appears in a cell in the table.
    The list works fine for me, i get a Listvalue string from the following method
    //Part of FileList.java
    //tableTracks class constructor
    TableTracks tableTrack = new TableTracks();
    public void keyReleased(KeyEvent e) {
    switch(e.getKeyCode()) {
    case KeyEvent.VK_ENTER:
       value = jlst.getSelectedValue().toString();;
       if (value.endsWith(".wav"))
       iNameLen = value.length();
       value = value.substring(iEntryType,iNameLen);
       System.out.println("sending..... " + value);
       tableTrack.insertValue(value);
       break;
    }So far so good! in the above i call the insertValue method and below is that method
    //TableTracks.java
    void insertValue(String file)
      System.out.println("insertVal: " + file);
       table.setValueAt(file, 3, 3 );
    }in both of the system.out.println statements in the above 2 methods, the correct value is displayed. But it simply will not display the vlaue in the table.
    Before i added the List option to my program, i had it working by allowing the user to select a file name using a FileChooser. With this method, the table.setValue worked fine. But now, it will not.
    Any help or suggestions would be very greatly appreciated.
    cheers
    RC

    You probably defined the "table" variable twice. Once as a class variable and once as a local variable and your "insertValue" method is referring to the wrong variable and therefore updating the wrong table.

  • Updating JTable from data from resultset

    I have an athletics database, where the user updates an event and round e.g. 100M run Round 1. I then have a query which returns the 3 fastest times from each round for whatever event.
    Now on my JTable gui, the user chooses what event and round to update through 2 JCombo boxes, one for events, one for rounds. Now if the user chooses the round name final, i need the JTable to update the table with the three fastest times from rounds 1, 2 and 3.
    Whats the best way to do this? I was thinking putting all the different result sets into an array, and then through an if loop have somthing like
    if(roundType.equals (final))then in the body of this loop, create an instance of my JTable setting the rows for each column the the resultset data.
    Is this the right approach or any other advise?
    cheers

    You probably defined the "table" variable twice. Once as a class variable and once as a local variable and your "insertValue" method is referring to the wrong variable and therefore updating the wrong table.

  • Update JTable from a JDialog

    I'm wanting to update a JTable I have on a JFrame. This JFrame has a button on it which opens a JDialog box which populates a database. The main JFrame's JTable (ReceivedTable) holds this information. When a user inputs some more information and closes the dialog, I'd like to update the JTable in the main JFrame, but am not sure how to go about doing this. Can someone give me an idea to work from.
    Thanks.

    G'day mate,
    Make an extension of JDialog like so:
    //import appropriate classes here
    public class MyDialog extends JDialog implements ActionListener {
         //you would have some text fields or such here
         public MyDialog(Frame parent, String name) {
              super(parent, name, true);
              JPanel cp = (JPanel)getContentPane();
              //cp.add(fields here!);
              JButton submit = new JButton("Submit");
              submit.addActionListener(this);
              cp.add(submit);
         public void actionPerformed(ActionEvent ae) {
              Vector data = new Vector();
              //populate 2d data vector with data for the table
              Vector column_names = new Vector();
              //names for your table columns
              ((DefaultTableModel)((JFrame)getOwner()).getTable().getModel()).setDataVector(data, column_names);
              dispose();
    Note: In your JFrame you will need to define a method getTable().
    I think that should work for you... Obviously you'll have to add in a lot of code yourself, but that should be a reasonable skeleton.
    Good luck,
    Muel.

  • Updating Magazine from database source

    Hi,
    Some information that I need to manage in mu future magazine has to be updated from a database hosted on a server.
    Is there a way to do that ? I believe it is done with the webkit window ?
    What happens when my magazine id in offline mode (aka the iPad is diconnected from network ?)
    Regards,
    Frédéric

    Thanks for replying ceccs,
    I did try this by creating a backup vector of the database table. But everytime I changed the data in the Jtable this changed the backup one.
    I haven't got a clue as to why this is happening

  • Update JTable from String[][]

    Hello everyone, I have a JTable with a slightly customized DefaultTableModel shown below:
    DefaultTableModel tableModel = new DefaultTableModel(rowData, columnNames){
         private static final long serialVersionUID = 8655602888381735851L;
         @Override
             public boolean isCellEditable(int row, int column)
                         return false;
              };rowData is a String[][] of my data. When a user clicks a button, they add a row of data to the String[][]. I am wondering how I can update the JTable to reflect this change in the String[][]. Thanks!

    The problem with that is that I'm going to be performing various searches through the data, and those searches are performed on a TreeMap.
    rowData gets its data from the TreeMap, and is then displayedThe active verb does not describe the situation accurately: according to your code, rowdata is merely built from the TreeMap instance, and stuffed into a DefaultTableModel for display.
    When the user adds data, they add it to the TreeMap so that it can be searched.
    I can easily convert the data from the TreeMap to the String[][], but I don't know how to "redraw" the table with the new data.I assume the data is too big to repeat the process each time the user adds a row (build the new String[][], wrap it into a new DefaultTableModel instance and set the instance as the table's model).
    Another way is to duplicate the structure: when the user adds a row, add it into the searchable collection, and into the table model. But this costs twice the memory, and, again, I assume your data set is too large.
    A third, probably more elegant way is to build your own TableModel implementation: it could store a reference to the TreeMap instance, and an array converting the table's row index values to the tree's key value. That way the table model can be described in the active mode:
    "the JTable asks the model for cell values, and the model asks the tree for the corresponding data" :o)

  • Update JList from database table

    Hi! I have a JList that take some value from a mysql table. I want that the JList add or remove value when insert or delete row from db table.
    Can you help me?

    Well then you need to write the add/remove code of the JList yourself. So when ever you updated the database you update the ListModel as well.
    Read the JList API and follow the link to the Swing tutorial on "How to Use Lists" for a working example that dynamically updates a ListModel.

  • How to update jTable from user input?

    I create one jTable with 2 rows and 3 columns. the jtable colums contains deviceIP and Status. I am getting device IP from user input through jTextfield. so, when user enter IP and click add button, it must added in the jTable rows one by one.
    how can I add it by user enter the IP. Also, I want to update the status column value by "UP" or "DOWN" by just getting string value from other function.
    but, my problem is i need to update the correct IP status value to correct column (ie., I want to put IP 1(row 1) status to column 1 in status column list.
    I don't know about jTable .
    If any one have any examples please give me.

    use
    ((DefaultTableModel)jTable.getModel()).addRow(Object[]);
    Object[] is the array of row data values you want to insert;

  • How to put data in JTable from database

    hi everyone,
    i want to query the databse and put the result in the JTable and if possible i want to edit some information. For example: i have 5 records in the database query them and place them in JTable and each record has its own status. if i want to change the status For Example: the status of the 4 records are "Cleared" and the other one is "RELEASEd" so if i have JCombo Box to set the 4 records in to RELEASED status and then save the changes is that possible?
    thank you
    dhing

    In [url /thread.jsp?forum=54&thread=387565]this thread I describe how to use a result set as a basis for table data. Check some database tutorials for information on getting a result set.

  • Update jtable from other window

    Hi !
    I have a jtable in window #1.
    When choose row I opened window #2.
    In window #2 I update sme details and want the
    table in window #1 to update.
    How can I do it ?
    Thank you for your help

    hi,
    1. In Win2 make a 'linked' object-variable to Win1, like:
    puplic javax.swing.JFrame Win2 extends JFrame{
       //* as type the class of your own win1! not a common window (javax.swing.JFrame)!
       private Win1 myWin1 = null;
       public Win2(Win1 parWin1){ window javax.swing.
          this.myWin1 = parWin1
    }2. Make a public getter-methode for your JTable in Win1
    puplic javax.swing.JFrame Win1 extends JFrame{
       private javax.swing.JTable myTable1 = null;
       public javax.swing.JTable getJTable(){
          return this.myTable1;
    }3. call your win2 with the new constructor
       Win2 myWin2 = new Win2(this);
       myWin2.show();4. Now you can work in Win2 with your JTable with
       ... this.myWin1.getTable1.....cu
    Oliver SCORP
    ps: normally you don't have to update your JTable - you have to do this with the (Data) Model of your JTable

  • Re: ArrayIndexOutOfBoundsException when updating JTable from SwingWorker

    This is a common threading bug and there is a simple fix. You may only modify a visible component from the Event Dispatcher Thread.
    You are modifying the table model (which is part of a visible component) from an application thread (the swing worker).
    Even through you lock it or something like that, thats not the right way to do it. Don't write to the table model from another thread.
    The actual exception is that the EDT thread is painting the table rows while the swing worker is removing table rows, so you have the classic producer/consumer thread problem. The fix is not to use locks but instead use the Swing single thread rule, which is that only the EDT thread may modify a visible component. There is a lot of info on the java tutorials about swing threading.

    Thanks a lot, for some reason I neglected to try using SwingUtilities.invokeLater in my attempts to fix the problem! This has solved it.

Maybe you are looking for