Deleting a row from a JTable using a custom TableModel

Before I waste any of your time I would like to go ahead and just say that I have searched through the forum using "delete row from Jtable" as the search keywords and while I have found very closely related issues, they have not solved my problem. I have found code postings by carmickr and his arguments as to why we should use DefaultTableModel instead of having created our own custom TableModel, and while I do agree, I just am not quite confident enough in applying it to my scenario. See I am reading from a file a bunch of Contractor objects and I am stuffing it into an arraylist which I am using in the following code posting to populate my TableModel which the JTable object in the gui then uses.

My problem is that everything works except when I delete and when I delete I understand that the index is changing because I just removed a row from the arraylist object. Suppose I have 33 rows displaying in the GUI. Now after I delete say row #23, the delete function works and dutifuly the row disappears from the table, but if I try to delete a row say...the last row, it does not work and throws me an IndexOutOfBoundsException which totally makes sense. My question is how do I go about fixing it? Do I have to do something with the setRowCount method?

Any help is appreciated.

Cheers,

Surya

/*

* ContractorTableModel.java

*

* Created on January 12, 2006, 11:59 PM

*

*/

package code.suncertify.gui;

import java.util.ArrayList;

import java.util.logging.Logger;

import javax.swing.table.AbstractTableModel;

import code.suncertify.db.Contractor;

/**

*

* @author Surya De

* @version 1.0

*/

publicclass ContractorTableModelextends AbstractTableModel{

/**

* The Logger instance. All log messages from this class are routed through

* this member. The Logger namespace is <code>sampleproject.gui</code>.

*/

private Logger log = Logger.getLogger("code.gui");

/**

* An array of <code>String</code> objects representing the table headers.

*/

private String [] headerNames ={"Record Number","Contractor Name",

"Location","Specialties","Size","Rate",

"Owner"};

/**

* Holds all Contractor instances displayed in the main table.

*/

private ArrayList <Object> contractorRecords =new ArrayList<Object>(5);

/**

* Returns the column count of the table.

*

* @return An integer indicating the number or columns in the table.

*/

publicint getColumnCount(){

return this.headerNames.length;

}

/**

* Returns the number of rows in the table.

*

* @return An integer indicating the number of rows in the table.

*/

publicint getRowCount(){

return this.contractorRecords.size();

}

/**

* Gets a value from a specified index in the table.

*

* @param row An integer representing the row index.

* @param column An integer representing the column index.

* @return The object located at the specified row and column.

*/

public Object getValueAt(int row,int column){

Object [] temp = (Object[]) this.contractorRecords.get(row);

return temp[column];

}

/**

* Sets the cell value at a specified index.

*

* @param obj The object that is placed in the table cell.

* @param row The row index.

* @param column The column index.

*/

publicvoid setValueAt(Object obj,int row,int column){

Object [] temp = (Object []) this.contractorRecords.get(row);

temp [column] = obj;

}

/**

* Returns the name of a column at a given column index.

*

* @param column The specified column index.

* @return A String containing the column name.

*/

public String getColumnName(int column){

return headerNames[column];

}

/**

* Given a row and column index, indicates if a table cell can be edited.

*

* @param row Specified row index.

* @param column Specified column index.

* @return A boolean indicating if a cell is editable.

*/

publicboolean isCellEditable(int row,int column){

returnfalse;

}

/**

* Adds a row of Contractor data to the table.

*

* @param specialty

* @param recNo The record number of the row in question.

* @param name The name of the contractor.

* @param location Where the contractor is located

* @param size Number of workers for the contractor

* @param rate The contractor specific charge rate

* @param owner Name of owner

*/

publicvoid addContractorRecord(int recNo, String name,

String location, String specialty,

int size,float rate, String owner){

Object [] temp ={new Integer(recNo), name,

location, specialty,new Integer(size),

new Float(rate), owner};

this.contractorRecords.add(temp);

fireTableDataChanged();

}

/**

* Adds a Contractor object to the table.

*

* @param contractor The Contractor object to add to the table.

*/

publicvoid addContractorRecord(Contractor contractor){

Object [] temp ={new Integer(contractor.getRecordNumber()),

contractor.getName(), contractor.getLocation(),

contractor.getSpecialties(),new Integer(contractor.getSize()),

new Float(contractor.getRate()), contractor.getCustomerID()};

this.contractorRecords.add(temp);

fireTableDataChanged();

}

/**

* Deletes a row of Contractor data to the table.

* @FIXME Now that I deleted a row then I will have to reset the internal structure so that I can delete again

* @param recNo The record number of the row in question.

*/

publicvoid deleteContractorRecord(int recNo){

contractorRecords.remove(recNo - 1);

fireTableRowsDeleted(recNo -1, recNo - 1);

}

}

[9100 byte] By [suryadea] at [2007-10-2 10:16:46]
# 1

One other thing I would like to add is that in the ContractorTableModel, the arraylist is containing a bunch of Contractor objects. The structure of the Contractor object has a recordNumber field variable. In the Jtable there is a column that says record number as can be seen from the header names posted in the above code. So the first Contractor object in the JTable display has a value of 1 in that Record Number column. The second Contractor object has a display of 2 and so on. So when I am selecting say row 10 and deleting it, I am basically removing 10 - 1 index from the arraylist in the TableModel. Hope that makes sense. That is why you will see me subtracting 1 in the deleteContractorRecord function.

Surya

suryadea at 2007-7-13 1:42:25 > top of Java-index,Desktop,Core GUI APIs...
# 2

If you are trying to delete multiple rows that have been selected, then chances are the problem is not with your TableModel but with your delete logic.

The easiest way to solve the problem is to build you loop such that you delete the highest row number first and then work back to zero. That way the index numbers from you getSelectedIndexes() will always be in sync.

Posting the TableModel without a test program really isn't of much benefit.

camickra at 2007-7-13 1:42:25 > top of Java-index,Desktop,Core GUI APIs...
# 3

Wow that was a very quick response. Thanks camickr. I am only trying to delete a single row. I do not know how to go about posting a test program for the code I have posted above because honestly the gui itself is 800 lines of code, and then the file reading class is quite funky in itself. I can maybe email you the entire Netbeans project including code so if you are using Netbeans 5 RC2 you can run the code and see for yourself, but that would not be considerate of me.

See I am trying to delete any row at any time...but only one at a time not multiple rows...so if a user decides to delete row 23 and then tries to delete the last row which happens to be row 33 in my case, my setup should be smart enough to still allow to delete the row.

suryadea at 2007-7-13 1:42:25 > top of Java-index,Desktop,Core GUI APIs...
# 4

Well you have to validate that you indexes are correct.

If you select the first row in a table, then when you use table.getSelectedRow() you will receive the value 0, since indexes into the TableModel use 0 as the starting offset. Same thing for an ArrayList, it uses 0 as the offset.

So, I don't understand why your delete code is using "index - 1"?

Also does you table start with 33 rows, because if you delete row 23, then you can't delete row 33, you must now delete row 32 since every row has been shifted down.

So basically, we can't help with you problem because we don't know the structure of your data and how you determine the index to delete.

camickra at 2007-7-13 1:42:25 > top of Java-index,Desktop,Core GUI APIs...
# 5

camickr I solved my problem. Chatting with you has been very helpful. I was doing something extremely stupid haha now that I think about it. If you are interested I would try to explain what I did but I dont want to take up any more of your time. I appreciated the time and your patience that you have provided. I really do. Thanks!

Cheers,

Surya

suryadea at 2007-7-13 1:42:25 > top of Java-index,Desktop,Core GUI APIs...
# 6

> Chatting with you has been very helpful. I was doing something extremely stupid haha now that I think about it

Which is why I always ask for a simple program that demonstrates the problem. If you simplify the 800 lines of code in your program and get rid of all the junk that isn't related to your problem then its easier to see what might be wrong.

camickra at 2007-7-13 1:42:25 > top of Java-index,Desktop,Core GUI APIs...
# 7

Hi,

My abstractTableModel stores the data in a array of array

Object[][] data;

and when I wanted to implement the delete row I tought that abstractTableModel provide this just like defaulttableModel thing that is wrong. and after a long work I have to change array of array to a vector of vector that provide remove methode.

how can perform the remove without changing the array of array ?

thank you

8578736137593028604a at 2007-7-13 1:42:25 > top of Java-index,Desktop,Core GUI APIs...
# 8

> My abstractTableModel stores the data in a array of array

AbstractTableModel does not store any data. You have extended the AbstractTableModel to provide some funtionality that store data in an array or arrays.

> how can perform the remove without changing the array of array ?

By doing exactly what a Vector does. A Vector simply uses an array to store the data. When the Vector grows in size it creates a bigger array and copies the old array to the new array.

So you can rewrite all the code yoursefl, of just simply use the Vector.

camickra at 2007-7-13 1:42:25 > top of Java-index,Desktop,Core GUI APIs...
# 9
thnak you for the explanation. the remove method is working now.
8578736137593028604a at 2007-7-13 1:42:25 > top of Java-index,Desktop,Core GUI APIs...
# 10
Hi How have you solved your problem? I've got the same problem. I don't know how to delete the row. Please send me your corrected ContractorTableModel class. Thanks alot!!Cheers Dave
butzelmanna at 2007-7-13 1:42:25 > top of Java-index,Desktop,Core GUI APIs...
# 11

Hello...

I am having a similiar problem.

I am reading a .dbf file and displaying it in a jtable.

In order to display the dbf table I had to create my own AbstractTableModel.

I want to be able to select one row and click on a button and for the row and the info to be erased and then the jtable updated.

Can anyone help?

I already tried with the removerRow() but my AbstractTableModel doesn't have that method implemented.

I have also tried casting the abstracttablemodel to a DefaultTableModel but I get a ClassCastException, so im guessing that isn't possible.

Any help would be greatly appreciated!

Ericka =)

distantwondera at 2007-7-13 1:42:25 > top of Java-index,Desktop,Core GUI APIs...
# 12

> In order to display the dbf table I had to create my own AbstractTableModel.

Why? Whats wrong with the DefaultTableModel

Anyway, if you created your own TableModel by extending the AbstractTableModel, then you are the only person who knows what your data structure is like to store the data in the TableModel. So you are the only person who can write a "removeRow" method for your TableModel. There is no generic solution since you are using custom code.

If you want ot get an idea on how to write the "removeRow" method, then take a look at the source code of the DefaultTableModel and then try to incoroparate the concepts into you code.

camickra at 2007-7-13 1:42:26 > top of Java-index,Desktop,Core GUI APIs...
# 13
Hey!Thanks for the prompt response =)Where can I find the source code for the DefaultTableModel?
distantwondera at 2007-7-13 1:42:26 > top of Java-index,Desktop,Core GUI APIs...
# 14
> Where can I find the source code for the DefaultTableModel? The source code comes with the JDK. In JDK1.4.2 its called src.zip and is found at the root directory where you installed the JDK.
camickra at 2007-7-13 1:42:26 > top of Java-index,Desktop,Core GUI APIs...
# 15

Hello,

I have the following code:

package test;

import java.awt.Component;

import java.awt.event.ActionEvent;

import java.awt.event.ItemEvent;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.math.BigDecimal;

import java.util.Vector;

//import java.util.GregorianCalendar;

import javax.swing.JMenuItem;

import com.linuxense.javadbf.*;

import com.linuxense.javadbf.DBFReader;

import javax.swing.*;

import hirnstrom.javadbf.*;

import hirnstrom.app.sql.SqlFactory;

import hirnstrom.app.DbfFile;

import hirnstrom.app.DbfTable;

import hirnstrom.app.DbfViewer;

import hirnstrom.app.DbfFileFilter;

import javax.swing.event.EventListenerList;

import javax.swing.event.ListSelectionEvent;

import javax.swing.event.ListSelectionListener;

import javax.swing.event.TableModelEvent;

import javax.swing.event.TableModelEvent;

import javax.swing.event.TableModelListener;

//import java.util.Calendar;

//import java.util.Date;

//import java.util.Timer;

//import java.util.TimerTask;

import test.AbstractTableModelListener;

import java.io.DataOutput;

import javax.swing.table.AbstractTableModel;

import javax.swing.table.DefaultTableModel;

import javax.swing.table.TableModel;

import test.AbstractTableModelListener;

import test.MyTableModelListener;

import xBaseJ.*;

/*

* Interface.java

*

* Created on December 18, 2006, 3:47 PM

*/

/**

*

* @author distantwonder

*/

public class Interface extends javax.swing.JFrame {

/** Creates new form Interface */

public Interface()

{

super( "Point Of Sale");

initComponents();

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JMenuItem jm_nota = new JMenuItem();

JMenuItem jm_fact = new JMenuItem();

JMenuItem jm_cancelar = new JMenuItem();

JMenuItem jm_exit = new JMenuItem();

JMenuItem jm_cancel = new JMenuItem();

JMenuItem jm_cobrar = new JMenuItem();

jm_nota.setText("Nueva nota de emergencia");

jm_fact.setText("Nueva factura de emergencia");

jm_exit.setText("Salir del sistema");

jm_cancel.setText("Cancelar operacin");

jm_cobrar.setText("Cobrar factura");

jMenu_archivo.add(jm_nota);

jMenu_archivo.add(jm_fact);

jMenu_archivo.add(jm_cancelar);

jMenu_archivo.addSeparator();

jMenu_archivo.add(jm_cobrar);

jMenu_archivo.addSeparator();

jMenu_archivo.add(jm_cancel);

jMenu_archivo.addSeparator();

jMenu_archivo.add(jm_exit);

JMenuItem jm_tarjeta = new JMenuItem();

JMenuItem jm_cheques = new JMenuItem();

JMenuItem jm_devol = new JMenuItem();

jMenu_capturar.add(jm_tarjeta);

jMenu_capturar.add(jm_cheques);

jMenu_capturar.addSeparator();

jMenu_capturar.add(jm_devol);

jm_tarjeta.setText("Capturar datos tarjetas");

jm_cheques.setText("Capturar datos cheques");

jm_devol.setText("Devolucin dinero con nota de crdito");

JMenuItem jm_x = new JMenuItem();

JMenuItem jm_z = new JMenuItem();

JMenuItem jm_corte = new JMenuItem();

jm_x.setText("Reportar 'X'");

jm_z.setText("Reportar 'Z'");

jm_corte.setText("Sacar corte de caja");

jMenu_reportes.add(jm_x);

jMenu_reportes.add(jm_z);

jMenu_reportes.addSeparator();

jMenu_reportes.add(jm_corte);

JMenuItem jm_about = new JMenuItem();

JMenuItem jm_help = new JMenuItem();

jm_about.setText("Acerca de ...");

jm_help.setText("Ayuda");

jMenu_ayuda.add(jm_help);

jMenu_ayuda.addSeparator();

jMenu_ayuda.add(jm_about);

jToolBar6.setFloatable(false);

jToolBar1.setFloatable(false);

jToolBar2.setFloatable(false);

jToolBar3.setFloatable(false);

jToolBar4.setFloatable(false);

jButton10.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton10_ActionPerformed(evt);

}

});

jt.setVisible(false);

opendbf1();

jt.getModel().addTableModelListener(l);

}

public TableModelListener[] getTableModelListeners()

{

return (MyTableModelListener[])listenerList.getListeners(

MyTableModelListener.class);

}

// <editor-fold defaultstate="collapsed" desc=" Generated Code ">

private void initComponents() {

jFrame1 = new javax.swing.JFrame();

jToolBar1 = new javax.swing.JToolBar();

jButton1 = new javax.swing.JButton();

jButton2 = new javax.swing.JButton();

jToolBar2 = new javax.swing.JToolBar();

jButton3 = new javax.swing.JButton();

jToolBar3 = new javax.swing.JToolBar();

jButton7 = new javax.swing.JButton();

jButton4 = new javax.swing.JButton();

jButton6 = new javax.swing.JButton();

jButton5 = new javax.swing.JButton();

jToolBar4 = new javax.swing.JToolBar();

jButton8 = new javax.swing.JButton();

jButton9 = new javax.swing.JButton();

jButton11 = new javax.swing.JButton();

jScrollPane2 = new javax.swing.JScrollPane();

jt = new javax.swing.JTable();

jToolBar6 = new javax.swing.JToolBar();

jButton10 = new javax.swing.JButton();

jMenuBar1 = new javax.swing.JMenuBar();

jMenu_archivo = new javax.swing.JMenu();

jMenu_capturar = new javax.swing.JMenu();

jMenu_reportes = new javax.swing.JMenu();

jMenu_ayuda = new javax.swing.JMenu();

org.jdesktop.layout.GroupLayout jFrame1Layout = new org.jdesktop.layout.GroupLayout(jFrame1.getContentPane());

jFrame1.getContentPane().setLayout(jFrame1Layout);

jFrame1Layout.setHorizontalGroup(

jFrame1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)

.add(0, 400, Short.MAX_VALUE)

);

jFrame1Layout.setVerticalGroup(

jFrame1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)

.add(0, 300, Short.MAX_VALUE)

);

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/test/new_fac.gif")));

jButton1.setToolTipText("Nueva factura");

jButton1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

jToolBar1.add(jButton1);

jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/test/new_fac2.gif")));

jButton2.setToolTipText("Nueva nota");

jButton2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

jButton2.setMaximumSize(new java.awt.Dimension(41, 35));

jButton2.setMinimumSize(new java.awt.Dimension(41, 35));

jButton2.setPreferredSize(new java.awt.Dimension(41, 35));

jButton2.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton2ActionPerformed(evt);

}

});

jToolBar1.add(jButton2);

jToolBar2.setRequestFocusEnabled(false);

jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/test/efec.gif")));

jButton3.setToolTipText("Cobrar factura seleccionada");

jButton3.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

jButton3.setMaximumSize(new java.awt.Dimension(41, 35));

jButton3.setMinimumSize(new java.awt.Dimension(41, 35));

jButton3.setPreferredSize(new java.awt.Dimension(41, 35));

jButton3.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton3ActionPerformed(evt);

}

});

jToolBar2.add(jButton3);

jToolBar3.setRequestFocusEnabled(false);

jButton7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/test/remove.gif")));

jButton7.setToolTipText("Cancelar factura sin cobrar");

jButton7.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

jButton7.setMaximumSize(new java.awt.Dimension(41, 35));

jButton7.setMinimumSize(new java.awt.Dimension(41, 35));

jButton7.setPreferredSize(new java.awt.Dimension(41, 35));

jButton7.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton7ActionPerformed(evt);

}

});

jToolBar3.add(jButton7);

jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/test/tarj.gif")));

jButton4.setToolTipText("Capturar tarjeta de cr\u00e9dito");

jButton4.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

jButton4.setMaximumSize(new java.awt.Dimension(41, 35));

jButton4.setMinimumSize(new java.awt.Dimension(41, 35));

jButton4.setPreferredSize(new java.awt.Dimension(41, 35));

jToolBar3.add(jButton4);

jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/test/cheq.gif")));

jButton6.setToolTipText("Capturar cheques");

jButton6.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

jButton6.setMaximumSize(new java.awt.Dimension(41, 35));

jButton6.setMinimumSize(new java.awt.Dimension(41, 35));

jButton6.setPreferredSize(new java.awt.Dimension(41, 35));

jToolBar3.add(jButton6);

jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/test/undo_edit.gif")));

jButton5.setToolTipText("Devoluci\u00f3n de dinero con nota de cr\u00e9dito");

jButton5.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

jButton5.setMaximumSize(new java.awt.Dimension(41, 35));

jButton5.setMinimumSize(new java.awt.Dimension(41, 35));

jButton5.setPreferredSize(new java.awt.Dimension(41, 35));

jToolBar3.add(jButton5);

jToolBar4.setRequestFocusEnabled(false);

jButton8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/test/z.gif")));

jButton8.setToolTipText("Reporte Z");

jButton8.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

jButton8.setMaximumSize(new java.awt.Dimension(41, 35));

jButton8.setMinimumSize(new java.awt.Dimension(41, 35));

jButton8.setPreferredSize(new java.awt.Dimension(41, 35));

jToolBar4.add(jButton8);

jButton9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/test/cort.gif")));

jButton9.setToolTipText("Corte de Caja");

jButton9.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

jButton9.setMaximumSize(new java.awt.Dimension(41, 35));

jButton9.setMinimumSize(new java.awt.Dimension(41, 35));

jButton9.setPreferredSize(new java.awt.Dimension(41, 35));

jToolBar4.add(jButton9);

jButton11.setText("Salir");

jButton11.setToolTipText("Salir");

jButton11.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

jButton11.setMaximumSize(new java.awt.Dimension(41, 35));

jButton11.setMinimumSize(new java.awt.Dimension(41, 35));

jButton11.setPreferredSize(new java.awt.Dimension(41, 35));

jButton11.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton11ActionPerformed(evt);

}

});

jToolBar4.add(jButton11);

jt.setModel(new javax.swing.table.DefaultTableModel(

new Object [][] {

{null, null, null, null},

{null, null, null, null},

{null, null, null, null},

{null, null, null, null}

},

new String [] {

"Title 1", "Title 2", "Title 3", "Title 4"

}

));

jScrollPane2.setViewportView(jt);

jToolBar6.setRequestFocusEnabled(false);

jButton10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/test/refr.gif")));

jButton10.setToolTipText("Actualizar");

jButton10.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

jButton10.setMaximumSize(new java.awt.Dimension(41, 35));

jButton10.setMinimumSize(new java.awt.Dimension(41, 35));

jButton10.setPreferredSize(new java.awt.Dimension(41, 35));

jToolBar6.add(jButton10);

jMenu_archivo.setText("Archivo");

jMenuBar1.add(jMenu_archivo);

jMenu_capturar.setText("Capturar");

jMenuBar1.add(jMenu_capturar);

jMenu_reportes.setText("Reportes");

jMenuBar1.add(jMenu_reportes);

jMenu_ayuda.setText("Ayuda");

jMenuBar1.add(jMenu_ayuda);

setJMenuBar(jMenuBar1);

org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)

.add(layout.createSequentialGroup()

.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)

.add(layout.createSequentialGroup()

.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)

.add(jToolBar1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)

.add(layout.createSequentialGroup()

.add(90, 90, 90)

.add(jToolBar2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))

.add(layout.createSequentialGroup()

.add(140, 140, 140)

.add(jToolBar6, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))

.add(layout.createSequentialGroup()

.add(190, 190, 190)

.add(jToolBar3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 180, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))

.add(jToolBar4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))

.add(layout.createSequentialGroup()

.addContainerGap()

.add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 616, Short.MAX_VALUE)))

.addContainerGap())

);

layout.setVerticalGroup(

layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)

.add(layout.createSequentialGroup()

.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)

.add(jToolBar1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)

.add(jToolBar2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)

.add(jToolBar6, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)

.add(jToolBar3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)

.add(jToolBar4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)

.add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 222, Short.MAX_VALUE)

.addContainerGap())

);

pack();

}// </editor-fold>

private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {

id_num = jt.getSelectedRow();

jt.remove(id_num);

id_num = jt.getSelectedRow();

//jt.setValueAt(null, 0,3);

//for(int v=0; v <= 31; v++)

//{

//Object objeto = null;

//jt.setValueAt("",id_num, v);

//System.out.println(v);

//System.out.println(jt.getValueAt(id_num,v));

//

//}

//jt.updateUI();

//jt.revalidate();

//jt.repaint();

System.out.println("lalala");

//// rows = jt.getRowCount();

////cols = jt.getColumnCount();

//// JTable jt2 = new JTable();

//// this.jt = jt2;

//id_num = jt.getSelectedRow();

////DefaultTableModel dft= new DefaultTableModel(rows,cols);

//// jt2.setModel(dft);

//AbstractTableModel dataModel2 = (AbstractTableModel) jt.getModel();

//this.jt2 = jt;

//jt2.getUI();

//jt.revalidate();

//jt.setUI(jt2.getUI());

//

//

////jt.setModel(dataModel2);

//

////dft = (DefaultTableModel) jt.getModel();

////dft.setDataVector(jt.getColumnModel());

////jt.setModel(dft);

//

//

////jt.setModel(dataModel);

////jt.setModel(dataModel2);

////AbstractTableModel dataModel2 = (AbstractTableModel) jt.getModel();

////dataModel = (DefaultTableModel) dataModel;

////DefaultTableModel dataModel = (DefaultTableModel) jt.getModel();

//TableModelEvent tme = null;

//AbstractTableModelListener atml;

//

////jt.setModel(DefaultTableModel);

////DefaultTableModel dataModel = (DefaultTableModel) jt.getModel();

//try

//{

//

//System.out.println(id_num);

////jt.setModel(dataModel2);

////((AbstractTableModel)jt.getModel()).fireTableRowsDeleted(id_num,id_num+1);

//// jt.removeRowSelectionInterval(id_num,id_num);

//jt.removeAll();

//jt.revalidate();

//jt.repaint();

//int id_num2 = id_num+2;

//jt.removeRowSelectionInterval(id_num,id_num);

//jt.remove(jt.getSelectedRow());

//jt.remove(id_num);

//

//System.out.println(id_num+"\n" + id_num2);

////

////jt.revalidate();

////jt.repaint();

////fireTableDataChanged();

//

//}

//catch(IndexOutOfBoundsException iobe)

//{

//System.out.println(iobe);

//}

//catch(IllegalArgumentException iae)

//{

//System.out.println(iae);

//}

//// jt.revalidate();

////opendbf1();

////jt.revalidate();

////jt.repaint();

//

////DefaultTableModel dataModel = (DefaultTableModel) jt.getModel();

//

}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

Main.interfaz2_nota();

}

private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

dispose();

}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

id_num = (jt.getSelectedRow());

System.out.println(jt.getSelectedRow());

getid();

interfaz2_();

// Interface2.setTextFields();

}

public static void main(String args[]) {

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new Interface().setVisible(true);

}

});

}

// public class updateDBF extends TimerTask

//{

//public void run() {

//i++;

//System.out.println(i);

//opendbf1();

//if(i >= 10)

//{

//i = 0;

//timer = new Timer();

//}

//

//}

//

//}

//public void counter()

//{

// secs = calendar_.get(Calendar.SECOND);

// if(secs == 5 | secs == 25 | secs == 45)

// {

// opendbf1();

// }

// else

// {

// do

// {

//secs = calendar_.get(Calendar.SECOND);

// }

// while(secs !=5);

// }

// }

public void getid()

{

jt.updateUI();

try

{

blah = jt.getValueAt(id_num,0);

}

catch(ArrayIndexOutOfBoundsException aioobe)

{

JOptionPane.showMessageDialog(frame, "Error! Favor de seleccionar una factura.", "Point of Sale", JOptionPane.ERROR_MESSAGE);

}

if(blah != null)

{

select = 1;

}

if(blah == null)

{

select = 0;

}

if(select ==1)

{

for(int v=0; v <= 31; v++)

{

if (v==0)

{

blah = (jt.getValueAt(id_num, v));

System.out.println(blah);

num_parte1 = (String)(blah);

System.out.println(num_parte1);

v++;

}

if(v==1)

{

blah = jt.getValueAt(id_num, v);

System.out.println(blah);

// double cant = blah.toString();

String cant = blah.toString();

cantidad1 = Double.parseDouble(blah.toString());

System.out.println(cantidad1);

v++;

}

if(v==2)

{

blah = jt.getValueAt(id_num, v);

System.out.println(blah);

um1 = (String) blah;

System.out.println(um1);

v++;

}

if(v==4)

{

blah = jt.getValueAt(id_num, v);

System.out.println(blah);

descrip1 = (String) blah;

System.out.println(descrip1);

v++;

}

if(v==6)

{

blah = jt.getValueAt(id_num, v);

System.out.println(blah);

precio1 = Double.parseDouble(blah.toString());

System.out.println(precio1);

v++;

}

if(v==8)

{

blah = jt.getValueAt(id_num, v);

System.out.println(blah);

desc1 = Double.parseDouble(blah.toString());

System.out.println(desc1);

v++;

}

if(v==15)

{

blah = jt.getValueAt(id_num, v);

System.out.println(blah);

vend1 = Integer.parseInt(blah.toString());

System.out.println(vend1);

v++;

}

if(v==17)

{

blah = (jt.getValueAt(id_num, v));

System.out.println(blah);

nombre_11 = (String)(blah);

System.out.println(nombre_11);

v++;

}

if(v==18)

{

blah = (jt.getValueAt(id_num, v));

System.out.println(blah);

nombre_21 = (String)(blah);

System.out.println(nombre_21);

v++;

}

if(v==19)

{

blah = (jt.getValueAt(id_num, v));

System.out.println(blah);

domicilio_11 = (String)(blah);

System.out.println(domicilio_11);

v++;

}

if(v==20)

{

blah = (jt.getValueAt(id_num, v));

System.out.println(blah);

domicilio_21 = (String)(blah);

System.out.println(domicilio_21);

v++;

}

if(v==21)

{

blah = (jt.getValueAt(id_num, v));

System.out.println(blah);

domicilio_31 = (String)(blah);

System.out.println(domicilio_31);

v++;

}

if(v==30)

{

blah = (jt.getValueAt(id_num, v));

System.out.println(blah);

factura1 = (String)(blah);

System.out.println(factura1);

v++;

}

}

}

// try

// {

// FileInputStream fis = new FileInputStream("f:/ventas01/ericka.dbf");

// DBFReader reader = new DBFReader(fis);

// FileOutputStream fos = new FileOutputStream("f:/ventas01/ericka2.dbf");

// String output;

// DataOutput out;

// DBFField field = (reader.getField(id_num+1));

// //String output = field.toString();

// //System.out.println(field2.toString());

//}

// catch(DBFException dbfe)

// {

// System.out.println("dbfe");

// }

// catch(FileNotFoundException fnfe)

// {

// System.out.println("fnfe");

// }}

}

public static void remover()

{

}

public void opendbf1()

{

jt.setVisible(true) ;

dbf = new DbfFile("f:/ventas01/ericka.dbf");

try

{

DbfTable tbl = new DbfTable(dbf);

jt = new JTable(tbl);

jt.setAutoResizeMode(0);

jScrollPane2.getViewport().add(jt);

jt.updateUI();

//count();

////int div50ab = 0;

////int e = 0;

////for(int v = 0; v>=0; v++)

//// {

//// int div50a = 0;

//// div50a = calendar_.get(Calendar.SECOND);

//// div50a = div50a%10;

////div50ab = div50a;

////e = v;

////}

////

////

////

//// if (div50ab == 0)

//// {

////jt.updateUI();

////System.out.println(e);

////i++;

////

//// }

}

catch(hirnstrom.javadbf.DBFException dbfe)

{

//println(dbfe.getMessage());

return;

}

// timer.schedule(new updateDBF(), 9000, 90000 );

}

private void jButton10_ActionPerformed(java.awt.event.ActionEvent ae)

{

opendbf1();

//counter();

}

private void interfaz2_() {

if(select ==1)

{

Main.interfaz2();

}

}

/*

// Variables declaration - do not modify

private javax.swing.JButton jButton1;

private javax.swing.JButton jButton10;

private javax.swing.JButton jButton11;

private javax.swing.JButton jButton2;

private javax.swing.JButton jButton3;

private javax.swing.JButton jButton4;

private javax.swing.JButton jButton5;

private javax.swing.JButton jButton6;

private javax.swing.JButton jButton7;

private javax.swing.JButton jButton8;

private javax.swing.JButton jButton9;

private javax.swing.JFrame jFrame1;

private javax.swing.JMenuBar jMenuBar1;

private javax.swing.JMenu jMenu_archivo;

private javax.swing.JMenu jMenu_ayuda;

private javax.swing.JMenu jMenu_capturar;

private javax.swing.JMenu jMenu_reportes;

private javax.swing.JScrollPane jScrollPane2;

private javax.swing.JToolBar jToolBar1;

private javax.swing.JToolBar jToolBar2;

private javax.swing.JToolBar jToolBar3;

private javax.swing.JToolBar jToolBar4;

private javax.swing.JToolBar jToolBar6;

private javax.swing.JTable jt;

// End of variables declaration

*/

// Variables declaration - do not modify

private javax.swing.JButton jButton1;

private javax.swing.JButton jButton10;

private javax.swing.JButton jButton11;

private javax.swing.JButton jButton2;

private javax.swing.JButton jButton3;

private javax.swing.JButton jButton4;

private javax.swing.JButton jButton5;

private javax.swing.JButton jButton6;

private javax.swing.JButton jButton7;

private javax.swing.JButton jButton8;

private javax.swing.JButton jButton9;

private javax.swing.JFrame jFrame1;

private javax.swing.JMenuBar jMenuBar1;

private javax.swing.JMenu jMenu_archivo;

private javax.swing.JMenu jMenu_ayuda;

private javax.swing.JMenu jMenu_capturar;

private javax.swing.JMenu jMenu_reportes;

private javax.swing.JScrollPane jScrollPane2;

private javax.swing.JToolBar jToolBar1;

private javax.swing.JToolBar jToolBar2;

private javax.swing.JToolBar jToolBar3;

private javax.swing.JToolBar jToolBar4;

private javax.swing.JToolBar jToolBar6;

public static javax.swing.JTable jt;

// End of variables declaration

String fields;

public DbfFile dbf;

//Calendar date = Calendar.getInstance();

int i =0;

//Timer timer = new Timer();

int secs = 0;

String get_id;

static int id_num =0;

public static String num_parte1;

public static double cantidad1;

public static String um1;

public static String descrip1;

public static double precio1;

public static double desc1;

public static double vretiva1;

public static int vend1;

public static String nombre_11;

public static String nombre_21;

public static String domicilio_11;

public static String domicilio_21;

public static String domicilio_31;

public static String factura1;

public static boolean borrar;

Object blah;

//GregorianCalendar calendar_ = new GregorianCalendar();

public static DefaultTableModel dataModel;

public TableModelEvent tme;

public TableModelListener l;

public static AbstractTableModel atm2;

private TableModel DefaultTableModel;

private TableModel dataModel2;

private static int rows;

public static Object data[][];

private static int cols;

private JTable jt2;

private Component frame;

private int select;

protected EventListenerList listenerList = new EventListenerList();

}

And I want to be able to delete a row I select when i push jButton7.

The TableModel code is the following:

/*

Created on 01.12.2004

Stefan Wagner for thbb

*/

package hirnstrom.app;

import java.math.*;

import java.util.*;

import javax.swing.table.*;

import hirnstrom.javadbf.DBFException;

/**

Nicht verwechseln mit DfB - Tabelle.

Vielmehr ein dBase-Tabellen-modell, welches die DBase-Typen, die in jTypes beim Lesen

des DbfFiles bereits in Java-kompatible Typen verwandelt worden sind, bereitstellt.

@author S. Wagner, thbb

*/

public class DbfTable extends AbstractTableModel

{

private int rows;

private int cols;

private List <String> colnames;

private Object [][] data;

private char [] jTypes;

/**

@param dbff

@throws DBFException

*/

public DbfTable (DbfFile dbff) throws DBFException

{

rows = dbff.getRows ();

cols = dbff.getCols ();

colnames = dbff.getNames ();

jTypes = dbff.getJTypes ();

if (dbff.getState()) data = dbff.getData ();

}

/*(non-Javadoc)

@see javax.swing.table.TableModel#getRowCount()

*/

public int getRowCount ()

{

return rows;

}

/*(non-Javadoc)

@see javax.swing.table.TableModel#getColumnCount()

*/

public int getColumnCount ()

{

return cols;

}

/*(non-Javadoc)

@see javax.swing.table.TableModel#getValueAt(int, int)

*/

public Object getValueAt (int row, int col)

{

Object o = null;

try

{

o = data [row][col];

if (o == null) return null;

// return o;

/*String s = o.toString ();

// if (row == col) System.out.print (data [row][col]);

if ((s.length () == 0) && jTypes [col] != 'S')

{

return null;

}

*/

switch (jTypes [col])

{

case 'S': return (String) o;

case 'M': System.err.println ("Memo-Field!"); return (String) o;

case 'B': return (Boolean) o;

case 'c': return (Character) o;

case 'd': return (Date) o;

case 'b': return (Byte) o;

case 's': return (Short) o;

case 'i': return (Integer) o;

case 'l': return (Long) o;

case 'I': return (BigInteger) o;

case 'D': return (BigDecimal) o;

case '0':

default:

System.err.println ("DbfTable.getValueAt()-> Unhandled default:typ = " + jTypes [col] + " val: " + o.toString ());

return " <?> ";

}

// */

}

catch (ClassCastException cce)

{

System.err.println ("DbfTable.getValueAt()-> cce r = " + row + "\tcol = " + col + "\ttyp = " + jTypes [col] + " " + cce.getMessage ());

return o.toString ();

}

catch (NullPointerException npe)

{

System.err.println ("DbfTable.getValueAt()-> npe r = " + row + "\tcol = " + col + "\ttyp = " + jTypes [col] + " " + npe.getMessage ());

return null;

}

}

public Class<?> getColumnClass (int idx)

{

//return "a String".getClass ();

switch (jTypes [idx])

{

case 'M':

case 'S': return String.class;

case 'c': return Character.class;

case 'B': return Boolean.class;

case 'd': return Date.class;

case 'b': return Byte.class;

case 's': return Short.class;

case 'i': return Integer.class;

case 'l': return Long.class;

case 'I': return BigInteger.class;

case 'D': return BigDecimal.class;

default:

System.err.println ("DbfTable.getColumnClass ()-> Unhandled default: " + jTypes [idx]);

return String.class;

}

}

/**

*/

public String getColumnName (int i)

{

return (String) colnames.get (i);

}

public boolean isCellEditable (int row, int col) { return false; }

}

Any help would be greatly appreciated. I'm stuck in a rut :S

Thanks!!! =)

distantwondera at 2007-7-20 20:39:28 > top of Java-index,Desktop,Core GUI APIs...
# 16
Also, I am using the abstract table model because i am using an api that has the abstract table model implemented from default. (See DBFTable code i posted earlier).Is it possible to maybe change the AbstractTableModel to a DefaultTableModel?
distantwondera at 2007-7-20 20:39:28 > top of Java-index,Desktop,Core GUI APIs...
# 17

Here is a simple example of create a table using the DefaultTableModel:

http://forum.java.sun.com/thread.jspa?forumID=57&threadID=627108

Start with that and add a button the uses the removeRow() method of the DefaultTableModel.

It you have problem then create you own thread descibing the problems. Don't clutter old threads.

If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program[/url] (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.

And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags[/url] so the code retains its original formatting.

A 300 line program is not a SSSCCE. 95% of the code you included above had nothing to do with a table and I'm not going to read through the 5% to try and find your problem.

camickra at 2007-7-20 20:39:28 > top of Java-index,Desktop,Core GUI APIs...