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();
}

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...        

  • How can I add a new row into an array bases on a1D array

    Hello,
    I build a FieldPoint application with LabView 7.1 RealTime. I've a measurement loop with 1Hz sample rate. I sample 5 channels and put them into a 1D array. Presently I write directly to a cvs file but this I've to cahnge because my loop slows down to 0.2 Hz.
    I want to sample my data the hole day (86400 loops) and save them inside of an array. When the time is over I want write the hole array (table) to the file.
    How I can do this or hoow I can add my 1D array to a new row in my 2D array?
    Thanks
    Thomas
    Thomas

    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...        

  • How can i add a new row in System Matrix passing itemcode and quantaty

    Hi All,
    I have to add new lines in the matrix system only through the itemcode and item quantity. I tried several ways without success. Maybe the following code help to explain what I'm trying to do.
    Someone already inserted rows in the matrix system? Can someone show me how I can do. This example is in C# but if someone has in VB I will apreciate.
    FormUID = SBO_Application.Forms.ActiveForm.UniqueID;
                f = SBO_Application.Forms.Item(FormUID);
                try
                    SAPbobsCOM.Recordset oRS;
                    oRS = ((SAPbobsCOM.Recordset)oCompany.GetBusinessObje
    SAPbobsCOM.BoObjectTypes.BoRecordset));
                    oItem = f.Items.Item("38");
                    oMatrix = ((SAPbouiCOM.Matrix)(oItem.Specific));
                    oEditText = ((SAPbouiCOM.EditText)oMatrix.Columns.Item(3).Cells.Item(oMatrix.RowCount - 1).Specific);
                    string Codigo = oEditText.Value; //Select the item number to use in strQuery
                    strQuery = "SELECT U_ART_COM FROM [@SB1EVOL_COMPOSTOS] where
    U_ART_PRI='" + Codigo.ToString();
                     oRS.DoQuery(strQuery);
                    if (oRS.RecordCount > 0)
                        oRS.MoveFirst();
                        numart = oRS.RecordCount;
                        f.Freeze(true);
                        for (j = 1; j <= numart; j++)
                            try
                                ItemCodeTXT = oRS.Fields.Item(0).Value.ToString();
                                oEditText = ((SAPbouiCOM.EditText)(oMatrix.Columns.Item(3).Cells.Item(oMatrix.RowCount).Specific));
                                oEditText.Value = ItemCodeTXT.ToString();
                                f.Update();
                                oRS.MoveNext();
                            catch (Exception oEx)
                                f.Freeze(false);
                                f.Update();
                                MessageBox.Show(oEx.Message + " j = " + System.Convert.ToString(j));
                        j = 0;
                        f.Freeze(false);
                        f.Update();
    In this example i try to add rows in Invoice matrix.
    Thanks in advance.
    Edited by: Luís Filipe Duarte on Jun 26, 2009 4:14 PM
    Edited by: Luís Filipe Duarte on Jun 26, 2009 4:17 PM

    Viva Vitor,
    Antes de mais obrigado pela resposta.
    È esse mesmo o meu objectivo. Passo a explicar qual é o objectivo deste desenvolvimento. O que se pretende é que quando um utilizador escreva o código de um artigo numa linha da matrix de um documento de venda o add-on vai ler esse artigo e de seguida consultar uma tabela de utilizador que ja esta criada para validar se esse artigo tem outros artigos associados, e se tiver, entao o addon tem que os escrever nas linhas imediatamente a seguir. Eu queria mesmo, era escrever qual era o artigo e qual a respectiva quantidade. Eu consigo encontrar qual o artigo que o utlizador escreve e qual os artigos associados. O meu problema acontece quando tendo adicionar as novas linhas.
    Com o codigo que se segue podes ver que estou a atribuir a uma EditText o codigo do artigo a escrever. O problema é se correr em modo debug consigo ver que a aplicação chega a essa linha 
    oEditText.Value = ItemCodeTXT.ToString();
    e volta para trás, ou seja entra num loop e nao sai daqui.
    if (oRS.RecordCount > 0)
                        oRS.MoveFirst();
                        numart = oRS.RecordCount;
                        f.Freeze(true);
                        for (j = 1; j <= numart; j++)
                            try
                                ItemCodeTXT = oRS.Fields.Item(0).Value.ToString();
                                oEditText = ((SAPbouiCOM.EditText)(oMatrix.Columns.Item(3).Cells.Item(oMatrix.RowCount).Specific));
                                oEditText.Value = ItemCodeTXT.ToString();
                                f.Update();
                                oRS.MoveNext();
                            catch (Exception oEx)
                                f.Freeze(false);
                                f.Update();
                                MessageBox.Show(oEx.Message + " j = " + System.Convert.ToString(j));
    Eu para adicionar uma nova linha o que tenho de fazer? não vasta passar a informação do item code?
    Este desenvolvimento é para implementar ecoreee no sap. Nao sei já tiveste alguma coisa dessas entre mãos.
    Obrigado mais uma vez pela atenção. Espero também um dia poder ajudar.
    Com os melhores cumprimentos.
    Luis duarte

  • 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/

  • Numbers: How do I add a new "Term" with all the formulas included to the GPA calculator template?

    I'm new to Numbers, and I am using the GPA calculator template. This includes 4 "terms" but I need 8. I have tried adding a new table but the formulas aren't included. How do I go about adding 4 new terms?

    Click on one of the four tables that represent Terms and click on the little circle that is in the very top left of the table, this will highlight the entire table.  Copy the table and paste a new one.  Relabel the table Term 5.
    In the GPA by term table, click in the cell that says Term 4, and add a new row; you can do this by holding Alt and pressing the down arrow.  Label the new cell Term 5, and in cell A6 and put the formula =Term 5::C6 and in B6 put the formula =Term 5::D6.
    Repeat for every term that you need.

  • How do I add my new lapttop to my family iTunes? I downloaded music, but cannot play it

    How do I add my new lap top to my family iTunes? I downloaded music, but cannot play it on my laptop

    There's a couple of ways to get through to the authorisation controls in the 11.0.x versions.
    The control is still in the Store menu, but first (if you're using iTunes versions 11.0.x) you might need to bring up the menu bar to see the Store menu.
    If you're using 11.0.x, click on the wee boxy icon up in the top-left corner of your iTunes to see the "Show Menu Bar" control, as per the following screenshot:
    Then you'll find the control in the Store menu:
    Alternatively, if you don't want to bring up the menu bar, it's still possible to get into the authorise controls via nested menus accessible from the wee boxy icon. Here's a screenshot of where to find them:

  • How do I add a new mailbox on my iPhone?

    How do I add a new mailbox on my iPhone 4S. I have tried going to the "Mailboxes" and selecting edit but that just takes me to the "New Message" screen.

    I don't need a "New Account". I would like to add some mailbox folders to store mail I choose to keep. Currently my choices are only:
    Inbox
    Drafts
    Sent
    Trash
    Does iPhone allow for additional folders within mailboxes?
    Re: How do I add a new mailbox on my iPhone? 

  • How do I add a new worksheet to an excell file utilizing a template with the report generation toolkit?

    Hello,
    My vi is gathering data from a piece of machinery. At varrious points durring the process, my vi must create printable reports. I am using the report generation tool kit to do this. What I want to do is for every report generated durring the run, add it as a new worksheet in an Excell workbook. My excell template works fine for the initial master report and I can add new data to new worksheets. What I am having a problem figuring out is how do I add the new data to a new worksheet using an excel template? I have 5 different reports that need to be generated at different times with some more often than others. I would like all these reports to be in the
    same master excel file. Thanks in advance
    -Greg
    Gregory Osenbach, CLA
    Fluke

    Hi Greg,
    There is no built-in support in LabVIEW to add a new worksheet to an existing Excel report simply because this functionality does not exist in the Excel application itself.
    My suggestion would be to open up the template you wish to use for the new worksheet. Copy the cells from the template and paste them into your new worksheet that you've created. Then close the original template and you have another copy of the template in which you can populate with data values.
    I have attached an example program of how to Copy and Paste a Cell in Microsoft 97 Using ActiveX in LabVIEW to this post. Hope this helps!
    Kileen C.
    Applications Engineer
    National Instruments
    Attachments:
    XL_cell_copy_and_paste.llb ‏76 KB

  • How do I add a new credit/debit card to my iTunes account? I've recently cancelled the credit card that had been set up, but I can't work out how to add a new one.

    How do I add a new credit/debit card to make payments on my iTunes account.?

    Accepted forms of payment  >  http://support.apple.com/kb/HT5552
    Changing Payment Information  >  http://support.apple.com/kb/HT1918
    If necessary... Contact iTunes Customer Service and request assistance
    Use this Link  >  Apple  Support  iTunes Store  Contact

  • How do I add a new font to the list?

    In "Tools/Options/Content/Advanced" how do I add a new font to the list? I have "Comic Sans MS" listed for one of the options, but the drop-down menu does not contain that option, so I can't select it for another font option.

    Thanks for your reply.
    As to your question: No, of course I wouldn't scroll down, it's in alphabetical order, so why would "C" for Comic Sans MS be anywhere but between B and D on the list?
    Now a question for you: If person or group was going to alphabetize a list and then break it down into sublists, why would he, she, they not include headers for each portion and maybe even indent each font name, so a person might have a chance of getting the drift?
    Also, how do you add new fonts to the list?

  • How do I add a new computer to the canning fuction on my

    How do I add a new computer to the scanning function on my PIXMA MX870? I can send print jobs to it from the new computer, but it tells me to "Set the PC to start scanning" when I try to scan to it. The old computer still accepts scanned images when it is turned on.

    Hi, Illiniboy67!
    So that the Community can help you better, we will need to know exactly which operating system is running on the computer you're trying to connect to the scanner, and how it's connected (USB, ethernet, or wi-fi). That, and any other details you'd like to give will help the Community better understand your issue!
    If this is a time-sensitive matter, our US-based technical support team is standing by, ready to help 24/7 via Email at http://bit.ly/EmailCanon or by phone at 1-800-OK-CANON (1-800-652-2666) weekdays between 10 AM and 10 PM ET (7 AM to 7 PM PT).
    Thanks and have a great day!

  • How do I add a new device to my existing email?

    How do I add a new device to my email account?

    You allowed someone that is not a family member to use your email address for their iTunes account?
    If so, what on earth were you thinking? This person can get a free email address at a number of places - AOL, Yahoo, Gmail, Hotmail to name a few.
    You will not be able to use your email address for your iTunes account now that you allowed someone else to use it for their iTunes account.

  • How do I add a new favourite to Safari?

    How do I add a new favourite to Safari?

    Tap Bookmark (tap to enlarge image)
    Save Location to Favorites (tap to enlarge image)

  • How do I add a new device to my icloud if it was stolen?  I need to track it

    How do I add a new device to my icloud.  My Ipad was stolen and I need to track it

    If you did not configure it for Find My Phone before it was stolen, then it's too late now.

Maybe you are looking for

  • Video as separate library set up question

    I have quite a large amount of purchased video on the internal harddrive of my powerbook. I would like to move most of video to a library on an external hard drive, but leave podcasts and music on the laptop. Can I create a new user account on the la

  • Calendar week numbers in Yosemite do not show entirely in Year View

    Sorry to say this but I'm actually a bit shocked at Apple's quality control to be posting this bug. Bugs are one thing but this is, in my view, absolutely unacceptable. Calendar Week Numbers are truncated in the Year View. Only the first digit is sho

  • Parameter screen and report in the same page?????

    Hi Gurus... Here is what i am trying to do ..I am trying to show the customization screen and the report in the same page 1.the user selects some data from the lov .. 2.Based on the lov selected field the below report should change .. like if the use

  • About ImageProducer and Image

    Hi, I have a question on ImageProducer and Image. Can I construct a java.awt.Image using a ImageProducer? I'm working on some image processing. I downloaded JIGL v1.6. JIGL has some classes to load image. However, I can't find any method to convert b

  • SSCM 2012 Endpoint Not Installing WMI not ready

    I am able to push out my client install using my default package i configured with some custom settings. Endpoint is enabled to install. I also deployed the endpoint custom policy to the computers. Teh SCCM client is installing on the client but Endp