Trying to add a new row to a JTable

I'm having trouble adding a row dynamically to a JTable. I've been able to populate the table with an array and that works well, but how do you add new rows after the program is running?

You need to make TableModel that does dynamic resizing od the underlying data 2d array. This one will resize for both rows and columns.
    private Vector dataNames= new Vector();
    private Vector dataData =new Vector();
        javax.swing.table.TableModel dataModel = new javax.swing.table.AbstractTableModel()
            public int getColumnCount()
                return dataNames.size();
            public int getRowCount()
                return dataData.size();
            public Object getValueAt(int row, int col)
                try
                    java.util.Vector v=(java.util.Vector)dataData.elementAt(row);
                    return v.elementAt(col);
                catch(Exception e)
                    System.out.println("e :"+e.getMessage());
                    return null;
            public String getColumnName(int column)
                return (String)dataNames.elementAt(column);
            public Class getColumnClass(int col)
                if(getValueAt(0,col)!=null)
                    return getValueAt(0,col).getClass();
                else
                    if(col==0)
                        return Integer.class;
                    else if(col==1 || col==2)
                        return Double.class;
                    else
                        return String.class;
            public boolean isCellEditable(int row, int col)
                if(col > 0 && col <4)
                    return mapTableEditable;
                else
                    return false;
            public void setValueAt(Object aValue, int row, int column)
                if(row>=dataData.size())
                    if(dataData.size()==0)
                        for(int i=0;i<row+1;i++)
                            dataData.addElement(new java.util.Vector());
                            java.util.Vector v2=(java.util.Vector)dataData.lastElement();
                            v2.setSize(getColumnCount());
                    else
                        java.util.Vector v1=(java.util.Vector)dataData.lastElement();
                        int dataSize=row-dataData.size()+1;
                        for(int i=0;i<dataSize;i++)
                            dataData.addElement(new java.util.Vector());
                            java.util.Vector v2=(java.util.Vector)dataData.lastElement();
                            v2.setSize(v1.size());
                java.util.Vector v=(java.util.Vector)dataData.elementAt(0);
                if(column>=v.size())
                    for(int i=0;i<dataData.size();i++)
                        v=(java.util.Vector)dataData.elementAt(i);
                        v.setSize(column+1);
                if(row<dataData.size())
                    v=(java.util.Vector)dataData.elementAt(row);
                    v.setElementAt(aValue,column);
        };

Similar Messages

  • How can I add a new row in a JTable dynamically?

    Dear Sir(s)
    I want to add a new row in a Jtable as I press enter key the time focus is on the last cell of the row? pls help

    TomDooley wrote:
    Hello,
    ...I write directly to a cvs file ...my loop slows down to 0.2 Hz
    Writing a series of 5 values to a file should not take so long. There is probably something wrong in the way you are saving your data. May be you should post a simplified version of your vi, so we could see how to improve your code.
    CC
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        

  • Dynamically adding a new row to a JTable

    Have anybody tried to add a new row to JTable? In the JTable if the user is editing the last row, another row should be created and displayed dynamically, without loosing the contents in the other rows and without any flickering effect. Is this possible in java applications or applets?
    -Madhuri.

    again, do all yoru work in the table model. make a class that implements the table model interface. if you mail me I can send you a table model I made(I have about 8) and you will see what to do from that. Its all about the table Model, not the table.
    Try using ArrayList instead of Vector unless you need it to be thread safe.

  • Trying to automatically add a new row w/o mutating table error...

    I'm using Oracle 10g express. I'm trying to automatically add a new row with the same e_ID, (RDD + 6 months) as the updated row when RC is updated. I'm fairly new to Oracle, so I need some help on creating a trigger. If you need more details let me know. Thanks in advance.
    create table E
    e_id number(6,0) not null,
    constraint e_pk primary key(e_id)
    create Table ER
    e_Id Number(6,0) Not Null,
    SC Date,
    RDD Date,
    RC Date,
    Constraint ER_Fk Foreign Key(E_Id) References E(E_Id)
    );

    mookjais wrote:
    I'm using Oracle 10g express. I'm trying to automatically add a new row with the same e_ID, (RDD + 6 months) as the updated row when RC is updated. I'm fairly new to Oracle, so I need some help on creating a trigger. If you need more details let me know. Thanks in advance.
    create table E
    e_id number(6,0) not null,
    constraint e_pk primary key(e_id)
    create Table ER
    e_Id Number(6,0) Not Null,
    SC Date,
    RDD Date,
    RC Date,
    Constraint ER_Fk Foreign Key(E_Id) References E(E_Id)
    );Do you mean following(example)?
    create trigger after_insert_e
    after
      insert
    on  e /*This is table name*/
    referencing new as new old as old
    for each row
    begin
    insert into  ER(e_Id,SC,rdd,rc)
    values(:new.ed_id,sysdate,sysdate,sysdate);
    end;

  • Need to add a new row at the end of the table

    Experts,
    working jdev 11.1.1.3.0
    i am adding row programetically, my requirement need to add the row at after last row.
    i tried different ways.
    Row newLastRow = getPWBBidLaneVO().last();
    int lastRowIndex = getPWBBidLaneVO().getRangeIndexOf(newLastRow);
    getPWBBidLaneVO().insertRowAtRangeIndex(lastRowIndex - 1,
    laneRow);
    this is giving --- java.lang.ArrayIndexOutOfBoundsException: 0
    and
    http://kohlivikram.blogspot.com/2008/10/add-new-row-in-adf-table-on-button.html --- its giving index out of bound because vo.getRangeSize() is 25. We set this value at vo for performance improment suggestions.
    is there a way to add a new row at the end of the table?

    Add this to the view row impl class
           public void insertRow(Row row) {
               //go to the end of Rowset if it has rows
               Row lastRow = this.last();
               if (lastRow !=null){
                    //insert new row at the end and make it current
                   int indx = this.getRangeIndexOf(lastRow)+1;
                   this.insertRowAtRangeIndex(indx,row);
                   this.setCurrentRow(row);
               }else { // empty Rowset
               super.insertRow(row);
               }

  • I am trying to add a new credit card and it keeps telling me that I have to enter a valid security code...I have tried 2 different cards and it is doing the same thing. How do I get past this?

    I guess it has been a year since I last purchased something on I-tunes and my account is saying that they couldn't authorize my card for some of my purchases.  I am trying to add a new credit card to clear this up and it keeps saying that I have to enter a valid security code.  I have tried 2 different cards and I get the same thing.  I have also added an I-tunes gift card and that isn't clearing up the money that I owe.  It is showing that I have a $25 credit for that.  How do I fix this, I have been trying for days and all I have got from the e-mail tech support is that its my credit card issuer that is causing the problem.  Thats not correct because one of the credit cards that I am trying to use, is a prepaid Visa gift card.  I know that these work on I-tunes because I have used them before in the past.  I am getting very frustrated with this whole process, I just want to clear up my account and buy some new music!! HELP!!

    You probably ran into blocks & locks.
    iTunes Store Support
    http://www.apple.com/emea/support/itunes/contact.html
    They'll sort it out.

  • How do I add a new row to an AbstractTableModel?

    I'm having an issue with adding new data to a table row. Every row I add contains the same data which is always the last data I grabbed from my database. I'm not sure if my issue has to do with how I set up the data to be passed or the table itself or both... Any help would be appreciated. It seems like the tablemodel is holding the memory spot ArrayList I'm passing. If I have to set up an arraylist of arraylists, to pass how do I do that?
    My output is always:
    1,4,Laser,10,120,100
    1,4,Laser,10,120,100
    1,4,Laser,10,120,100
    1,4,Laser,10,120,100
    Desired output:
    1,1,Beam,10,99,100
    1,2,Canon,10,120,100
    1,3,Missile,10,66,100
    1,4,Laser,10,120,100
         * Extract weaponIDs by hullType from weapon database
    private void setWeapons(int hullType){
    // equpModel is the tableModel
        equipModel.clearTable();
        Weapon tempWeapon = new Weapon();
        ArrayList newData = new ArrayList();
        for (Iterator <Weapon> i = dataBaseManager.weaponList.iterator(); i.hasNext(); ){
            tempWeapon = i.next();
            if (tempWeapon.weaponClass == hullType){
                newData.add(0,1);
                newData.add(1,tempWeapon.weaponID);
                newData.add(2,tempWeapon.weaponName);
                newData.add(3,tempWeapon.weaponCps);
                newData.add(4,tempWeapon.weaponMass);
                newData.add(5,tempWeapon.weaponCost);
                equipModel.insertRow(newData);
    }Here is a snipet from the table class
    public class GenTableModel extends AbstractTableModel {
      private ArrayList data; // Holds the table data
      private String[] columnNames; // Holds the column names.
       * Constructor: Initializes the table structure, including number of columns
       * and column headings. Also initializes table data with default values.
       * @param columnscolumns[] array of column titles.
       * @param defaultvdefaultv array of default value objects, for each column.
       * @param rowsrows number of rows initially.
      public GenTableModel(String[] columns, Object[] defaultv, int rows) {
        // Initialize number of columns and column headings
        columnNames = new String[ columns.length ];
        for(int i = 0; i < columns.length; i++) {
          columnNames [ i ] = new String(columns [ i ]);
        // Instantiate Data ArrayList, and fill it up with default values
        data = new ArrayList();
        for(int i = 0; i < rows; i++) {
          ArrayList cols = new ArrayList();
          for(int j = 0; j < columns.length; j++) {
            cols.add(defaultv [ j ]);
          data.add(cols);
       * Adds a new row to the table.
       * @param newrowArrayList new row data
      public void insertRow(ArrayList newrow) {     
        data.add(newrow);
        super.fireTableDataChanged();
       * Clears the table data.
      public void clearTable() {
        data = new ArrayList();
        super.fireTableDataChanged();
    }

    Hi thanks again for responding
    Here is the Initialization, including the panel and scrollpane it sits on.
          // Table attempt
            JPanel tablePanel = new JPanel(new BorderLayout());
            tablePanel.setBounds(PANEL_X+2*PANEL_DISTANCE, PANEL_Y, PANEL_WIDTH+300, PANEL_HEIGHT);
            title = BorderFactory.createTitledBorder(blackLine, "Table List");
            tablePanel.setBorder(title);
    // This is column tile plus one dummy initilization set.
            String[] columnNames = {"DB", "ID", "Name", "CPS", "Energy", "Mass", "Cost"};
            Object[] data = {new Integer(0),new Integer(0), "Empty", new Integer(0),
                        new Integer(0),new Integer(0),new Integer(0)};
    // here is the GenTableModel creation
            equipModel = new GenTableModel(columnNames, data, 1);
            equipmentTable = new JTable(equipModel);
            equipmentTable.setRowSelectionAllowed(true);
            equipmentTable.setFillsViewportHeight(true);
            equipmentTable.setColumnSelectionAllowed(false);
            TableColumn column = null;
            column = equipmentTable.getColumnModel().getColumn(0);
            column.setPreferredWidth(20);
            column = equipmentTable.getColumnModel().getColumn(1);
            column.setPreferredWidth(20);
            JScrollPane scrollPane = new JScrollPane(equipmentTable);
            tablePanel.add(scrollPane);
            add(tablePanel);
        Here is the full code for GenTableModel. It is as you guessed.
    public class GenTableModel extends AbstractTableModel {
      private ArrayList data; // Holds the table data
      private String[] columnNames; // Holds the column names.
      public GenTableModel(String[] columns, Object[] defaultv, int rows) {
        // Initialize number of columns and column headings
        columnNames = new String[ columns.length ];
        for(int i = 0; i < columns.length; i++) {
          columnNames [ i ] = new String(columns [ i ]);
        // Instantiate Data ArrayList, and fill it up with default values
        data = new ArrayList();
        for(int i = 0; i < rows; i++) {
          ArrayList cols = new ArrayList();
          for(int j = 0; j < columns.length; j++) {
            cols.add(defaultv [ j ]);
          data.add(cols);
      public int getColumnCount() {
        return columnNames.length;
      public int getRowCount() {
        return data.size();
      public String getColumnName(int col) {
        return columnNames [ col ];
      public Object getValueAt(int row, int col) {
        ArrayList colArrayList = (ArrayList) data.get(row);
        return colArrayList.get(col);
      public Class getColumnClass(int col) {
        // If value at given cell is null, return default class-String
        return getValueAt(0, col) == null ? String.class
                                          : getValueAt(0, col).getClass();
      public void setValueAt(Object obj, int row, int col) {
        ArrayList colArrayList = (ArrayList) data.get(row);
        colArrayList.set(col, obj);
      public void insertRow(ArrayList newrow) {     
        data.add(newrow);
        super.fireTableDataChanged();
      public void deleteRow(int row) {
        data.remove(row);
        super.fireTableDataChanged();
      public void deleteAfterSelectedRow(int row) {
        int size = this.getRowCount();
        int n = size - (row + 1);
        for(int i = 1; i <= n; i++) {
          data.remove(row + 1);
        super.fireTableDataChanged();
      public ArrayList getRow(int row) {
        return (ArrayList) data.get(row);
      public void updateRow(ArrayList updatedRow, int row) {
        data.set(row, updatedRow);
        super.fireTableDataChanged();
      public void clearTable() {
        data = new ArrayList();
        super.fireTableDataChanged();
    }

  • Add a new row at the top of a table in GUI

    Hi,
    I am using JDev 11.1.1.1.0. I need to be able to let users add a new row at the top of a table and not anywhere else in the middle of table rows. I cannot seem to find a way to do it. note that it does not matter where a new row gets inserted in the db, i am only concerned about restricting the insert in the GUI to the topmost line/row.
    Thanks,
    AJ

    Hi
    Can you try with writing your custom create method in application module and calling same from UI on command button action like
    public void createNewRow()
    ViewObjectImpl vo = getVO1();
    Row newRow= vo.createRow()
    vo.insertRowAtRangeIndex(0, newRow);
    Vikram

  • Error while trying to add a new field in search criteria by VO extension

    Hi,
    I am trying to add a new field by using the VO extension to a seeded OAF page used to search Repository contracts.
    I get the following error on opening the page after I have compiled my code on server and bounced apache.
    Message not found. Application: FND, Message Name: FND_VIEWOBJECT_NOT_FOUND. Tokens: VONAME =SSPN_AdvancedSearchAttributesPVO; APPLICATION_MODULE = oracle.apps.okc.repository.search.server.ContractsAdvSearchAM;
    I extended the AM also after this to include the extended VO but still the error comes.
    This page is a dynamic search page where the results change based on the different search criteria.
    Cheers
    Swati

    Hi,
    I extended the AM also after this to include the extended VO but still the error comes.There is no need to extend the AM for extending a VO. Hopefully the VO which u extending already attached to the AM oracle.apps.okc.repository.search.server.ContractsAdvSearchAM.
    Regards,
    Gyan

  • Trying to add a new node to OAS

    I'm trying to add a new node to our OAS server, and it always fails. Any hints on what I might be doing wrong?

    every entry in an ldap directory must have some mandatory attributes, e.g. "objectClass". which objectclass your entry should belong to? add the objectClass-attribute to your entry!
    Regards!
    Rainer

  • 2 yrs worth of music on my ipod nano 5th gen just vanished while I was trying to add four new tracks.

    Most of the music I've put on my ipod nano 5th gen in the last 2 years just vanished while I was trying to add four new tracks. Stuff from before that seems to be still there (I add stuff manually, not sync, and the ipod wasn't full). It was a bit glitchy as soon as I plugged it in to update - threw up a few error messages, decided to verify my ipod a couple of times, After that, once or twice itunes seemed to lose the ipod completely, although as far as the laptop was concerned it was definitely still connected, so i went for the 'safe to remove hardware' option and reconnected...
    I'm guessing somewhere in the midst of whatever was going on there, something got confused or corrupted, but I have no way to tell what... Ipod seems to think it is using less of its capacity now, but I don't know whether to believe it or not!
    Can I get this stuff back? It's not just stuff I bought from itunes, either - things I put on from cds have gone too. I have all the music either backed up or on cds, but I'm not in the same country as my cds right now - also rebuilding all of my playlists and trying to remember what went where is going to be a pain! Is there a quicker way than just doing it all over again?

    Downloading past purchases from the App Store, iBookstore, and iTunes Storehttp://support.apple.com/kb/HT2519
    Message was edited by: michael08081

  • My iphone 6 plus after updating to IOS 8.2 the touch id doesn't work neither in home unlock nor in app store and when i'm trying to add a new fingerprint it says ''failed unable to complete touch id setup.Please go back and try again'' .

    my iphone 6 plus after updating to IOS 8.2 seems to have a problem with the touch id witch doesn't work neither in home unlock nor in app store and when i'm trying to add a new fingerprint it says ''failed unable to complete touch id setup.Please go back and try again'' . I have multiple fingerprints and none of them appear to work.

    Hi Giannis,
    If you are having an issue with Touch ID not functioning as expected, I would suggest that you troubleshoot using the steps in this article -
    Use Touch ID on iPhone and iPad - Apple Support
    Start with the section titled Clean the Touch ID sensor and then Get help with Touch ID.
    Thanks for using Apple Support Communities.
    Sincerely,
    Brett L

  • Add a new row in Detail form in MASTER DETAIL FORM

    Hello Everyone,
    I need help on the following.I have master detail form .In detail form i have Add Row button which adds a new row and i have save button to save the record .But now if i am adding a row its not adding a new row .It says it process but didn't show the new row .
    Can somebody help me on this
    thanks in advance

    Hello,
    How many records do you show in your detaii region and how many are there for that master? Maybe the new row is in the next set of records - or at the 'bottom' of the last set of records?
    Did you check if the row is inserted in the database (and just didn't show up for one reason or another)?
    Greetings,
    Roel
    http://roelhartman.blogspot.com/
    http://www.bloggingaboutoracle.org/
    http://www.logica.com/

  • Trying to add the new year 2012 to posting periods

    I am trying to add the new 2012 months in posting periods in order to allow us to post some invoices that have terms due in 2012. First, when I go to add a new period the "category" feild is missing. Im guessing this has to be added somewhere else but I am not sure. Second, When I go to add the actual month for January 2012, I get the error "Enter Valid code [Posting Period -Period Code], '-' [Message 173-36]. Not really sure why I cant add this but I am guessing there is a step before I am missing. Any suggestions please...thank you!

    I figured out how to add it, I was adding the month as 2012-01, yet I only had to put 2012 and it would pre-fill in the dates then. Thanks anyways!

  • I am trying to add some new software and am told I have an incorrect software that I already confirmed is correct.  Can anyone help???

    I am trying to add some new software and am told I have an incorrect software that I already confirmed is correct.  Can anyone help???

    Please confirm you are actually running the ancient OS 8.6.
    What software is this?

Maybe you are looking for

  • Call transaction in new session (but only one)

    Dear all, as a hotspot functionality I would like to open a new transaction in a new session. For that reason, I use the FM ABAP4_CALL_TRANSACTION with the option STARTING NEW TASK. However I would like to restrict the new tasks in a way that only on

  • How to hide the table control column in module pool

    Dear Experts, Please help me on this I have 2 screens 9000 and 9001 . In screen 9000 I have 2 radio buttons if I select the 2nd radiobutton then the screen  9001 should display inthat some column has to be hide inthe table control. I have used this c

  • Resetting MacBook to a previous day to retrieve document

    Sunday night I wrote a very important document. On Monday, I accidentally saved something else in its place. Is there anyway I can reset my computer to Sunday night and retrieve the original document? Please help!

  • Opening RAW images in Camera Raw

    I owned a Nikon D80 and use Photoshop CS3.  I have used this program for years opeing my RAW images in the Camera Raw 4.0.  I just purchased a new Nikon D90 and now I can not open the RAW files in Photoshop at all.  Any suggestions?  Thanks, Debbie

  • File size will not automatically refresh in a finder window

    i'm not sure how long this has been going on, but i've noticed that when i save a file onto an external drive, the size listed will not update automatically and says "zero k". if i change the window view to thumbnails, or to columns, then back to fil