JTable - trying to delete a row of data using an Abstract TableModel
Hi Guys,
I am trying to delete a row of data on a JTable. What I am trying to accomplish is to highlight the row by a mouseclick,
then from the menu bar I am having the user select a "delete row" option. I am working with an abstract
Table Model with a deleteRow method. I know I am doing something wrong in this method but I'm not sure what... it is not deleting nor dynamically reflecting the deleted row of data on the JTable gui:
P.S. I am using a Vector of Vectors to store the data
Here are snippets of my main class and Abstract Table Model :
Main Class
Table definition and mouse listener:
usermodel = new DataFileTableModel("UserCtl.dat") ;
userTable = new JTable();
userTable.setModel(usermodel);
userTable.createDefaultColumnsFromModel();
userTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
upoint = evt.getPoint();
rowToBeDeleted = userTable.rowAtPoint(upoint);
Menu Selection which calls the deleteRow Method in the model:
deleteitem = new JMenuItem("Delete Row",'D');
editmenu.add(deleteitem) ;
deleteitem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int delresp = JOptionPane.showConfirmDialog(null,"Are you sure you wish to delete this row ?",null, JOptionPane.YES_NO_OPTION) ;
switch(delresp) {
case JOptionPane.NO_OPTION:
return;
case JOptionPane.YES_OPTION:
switch (tabnum)
case 0:
usermodel.deleteRow(rowToBeDeleted);
break ;
Here is my Abstract Table Model... the deleteRow method is at the bottom:
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.io.*;
import java.util.*;
public class DataFileTableModel extends AbstractTableModel {
protected Vector data;
protected Vector columnNames ;
protected String datafile;
public DataFileTableModel(String f){
datafile = f;
initVectors();
public void initVectors() {
String aLine ;
data = new Vector();
columnNames = new Vector();
try {
FileInputStream fin = new FileInputStream(datafile);
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
// extract column names
StringTokenizer st1 =
new StringTokenizer(br.readLine(), "|");
while(st1.hasMoreTokens())
columnNames.addElement(st1.nextToken());
// extract data
while ((aLine = br.readLine()) != null) {
StringTokenizer st2 =
new StringTokenizer(aLine, "|");
while(st2.hasMoreTokens())
data.addElement(st2.nextToken());
br.close();
catch (Exception e) {
e.printStackTrace();
public int getRowCount() {
return data.size() / getColumnCount();
public int getColumnCount(){
return columnNames.size();
public String getColumnName(int columnIndex) {
String colName = "";
if (columnIndex <= getColumnCount())
colName = (String)columnNames.elementAt(columnIndex);
return colName;
public Class getColumnClass(int columnIndex){
return String.class;
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
public Object getValueAt(int rowIndex, int columnIndex) {
return (String)data.elementAt( (rowIndex * getColumnCount()) + columnIndex);
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
data.setElementAt(aValue, (rowIndex * getColumnCount())+columnIndex) ;
fireTableCellUpdated(rowIndex, columnIndex);
public void addRow(Object[] aRow) {
for (int i=0; i < aRow.length; i++)
data.add(aRow);
int size = getRowCount();
fireTableRowsInserted(size-1,size-1);
public void deleteRow(int rowNo)
if (rowNo < 0 || rowNo >= getRowCount())
return;
int colCount = getColumnCount();
int index = colCount * rowNo;
System.out.println("in deleteRow Row = " + rowNo);
System.out.println("colCount = " + colCount);
System.out.println("index = " + index) ;
for (int d = index; d <= colCount; d++)
data.remove(d) ;
fireTableRowsDeleted(rowNo,rowNo) ;
Hi,
I can see one obvious problem. Your method to delete contains
for (int d = index; d <= colCount; d++)
data.remove(d) ;
which I think should be
for (int d = index; d <= colCount; d++)
data.remove(index) ;
because every time you remove the value at 'index' it replaces it with the value at 'index+1'.
I'm not sure that this is the only problem but ...
Roger
Similar Messages
-
JTable problem when deleting all rows and reinserting data,
Hi,
I have a JTable with an AbstractModelTable.
Some cells in the JTable have a custom cell editor. I am using
the cell editor that accepts only numeric values as explained in
the JTable tutorial (WholeNumberField).
- The JTable gets filled by choosing a value from a JList
for example:
1- choose a customer name from the customer JList
2- gets the customer order (database)
3- fills the Jtable with the customer data.
- When a customer is chosen from the Jlist I call a function
inside my table model. (This function removes all rows, clears the vector holding the data and calls fireTableRowsDeleted (firstRow, lastRow));
- Then I fill up the new data for this customer.
All of this works fine, except if I have entered a new value inside
one of the cell that has a customed cellEditor (ex: the Ordered column).
for example : user enters number 20 in the "ordered" column for customer A. Then changes his mind and chooses customer B from the JList. So the JTable gets cleared and refilled with the data of Customer B but the column "ordered" still has the value '20'
I would really appreciate any help...
ThanksDon't know is this will work, but try the following before updating the table:
if (table.isEditing())
table.removeEditor();Also, why do two TableModelEvent's..one for all getting deleted, one for the new filling. You could do one fireTableDataChanged after the new data is in. -
Trying to delete iPhoto 6 thumbsegment.data files crashes Mac OS 10.4
Summary:
Whenever I try to delete any of the thumb files from the iPhoto directory on my internal hard drive or my external backup drive, it crashes the computer (screen scrolls dark then says "Have to restart, hold button for several seconds" in multiple languages). This is true if I try to delete any single file or if I try to delete all the files (thumb32segment.data, thumb64segment.data, thumbJPGsegment.data). The panic message is:
panic(cpu 0 caller 0x00102854): jnl: transaction too big (1582592 >= 1572352 bytes, bufsize 8192, tr 0x2733f7c bp 0x280286d0)
The actual "transaction too big" numbers can vary. All my software is current as of last night. I'm running 10.4.6 and I have 150G drive with +10G free space, 1.25 GHz, 1GB memory.
Background:
I'm one of the people who experienced the extraordinarily sluggish version of iPhoto 6. In trying to fix it, I rebuilt my system from the hard drive up (including reinstalling everything)--no good. Apparently it was a known bug, a fix came out and my world was better. Until I tried to back up iPhoto.
I back up to an external hard drive by dragging and dropping.
1) Once I was sure the patch worked, I dragged the iPhoto folder from my internal drive to my backup drive...and the system crashed.
2) Figuring it was the old, buggy version causing the problem I dragged the old, external backup iPhoto folder to the trash and tried to empty the trash...and the system crashed.
3) After a file-by-file test, I determined it was the initial 2 thumbs (thumb32 and thumb64) from the buggy version causing the problem. One of the reasons I pay the Mac premium is because I don't want to be a sys admin, but nonetheless I went to Ihnatko's Mac OS X book and found the sudo command for forcing the trash to empty files (sudo chflags nouchg ~/.Trash/*), executed the command, emptied the trash...and the system crashed.
4) So I moved the old thumbs into a different folder on my external drive and dragged and dropped a backup. No problem. Until I tried to do it a second time after my next update to iPhoto and...the system crashed.
So now I have:
* old external backup (thumb32, thumb64)
* new external backup (thumb32, thumb64, thumbJPG)
* new internal source (thumb32, thumb64, thumbJPG)
and I can't backup or delete any of these files without the system crashing.
Does anyone have any ideas how I can get rid of the extraneous thumb files and get back to doing a simple drag-and-drop backup without crashing my system? (And yes, I've learned my lesson not to be an early adopter of iLife...but that doesn't help me now.)
FWIW, I'm having another problem with iPhoto or iTunes/iPod whereby iTunes/iPod has stopped recognizing iPhoto albums (http://discussions.apple.com/thread.jspa?threadID=530034&tstart=0). This happened long after the problem I've described here, but I'm including the link in case it's helpful.
G4 Mac OS X (10.4.6)Good morning Old Toad.
I did as you suggested:
1) Booted from install CD.
2) Ran Disk Utilities on internal hard drive--no repairs necessary. For good measure, did the same thing on external drive. Also no repairs necessary.
3) Checked software update--no updates found. About this Mac said I was already running 10.4.7. For good measure, I downloaded the latest and installed it. Since it let me run the install, I'm not sure if I installed something new or reinstalled what I already had.
4) I rebooted from CD, ran disk utilities, ran repair disk--no repairs necessary. Repaired permissions and a lot of permissions repaired.
5) Tried to delete the files and the same old thing happened: kernel panic. The specific message:
panic(cpu 0 caller 0x00102A08): jnl: transaction too big (1587712 >= 1572352 bytes, bufsize 8192, tr 0x29f1fb0 bp 0x2801de40)
So there's no change in my status.
I'm trying to delete the files because:
A) They already take .5 Gb.
B) I can't get rid of them ever. If I move the problem files to a different folder, I can only do one successful drag-and-drop backup to the external drive until the "new" thumb segments become unerasable just like the previous versions and crash the system.
C) I can't even "just" drag and drop every file/folder except the thumbs, because that ends up crashing the system as well. So I have to drag and drop every file/folder in the iPhoto hierarchy individually. Which makes me less inclined to backup, which defeats the purpose of a backup.
D) After the iPhoto fiasco I'm just crabby about all the Apple screw-ups I'm experiencing and I want to get them fixed.
Thanks for your help. Any additional suggestions would be appreciated.
G4 Mac OS X (10.4.6) -
Getting error while trying to delete multiple rows
Hi Experts,
Working in jdev 11.1.1.3.0 with ADF BC and rich faces.
i am trying to delete multiple records from the table, everything is working fine if i use filter or not using horizontal scroll bar of the table. if i try to delete last records on the table and the records are deleting from UI and from the DB also, but i am getting error like
ADFv:Count not find row:_$<to-calc>$_with key:oracle.jbo.key[2333] inside parent: XxwfsAvcardXXXXXXXVO1Iterator with key:null
I have changed my method with the below link
Re: JDev 11g-Multiple Row Selection Table-Ctrl+A error
but till i am getting the same error:
Method:
public void deleteRec(ActionEvent actionEvent) {
// Add event code here...
RowKeySet rowKeySet = (RowKeySet)this.embossTB.getSelectedRowKeys();
CollectionModel cm = (CollectionModel)this.embossTB.getValue();
Row specRow = null;
ArrayList rowList = new ArrayList();
int listLength = 0;
ArrayList<Number> printReqLST=new ArrayList<Number>();
ViewObject vo1=null;
boolean flag=false;
for (Object facesTreeRowKey : rowKeySet) {
cm.setRowKey(facesTreeRowKey);
JUCtrlHierNodeBinding rowData = (JUCtrlHierNodeBinding)cm.getRowData();
specRow = rowData.getRow();
rowList.add(specRow);
listLength++;
for (int index = 0; index < listLength; index++){
specRow = (Row)rowList.get(index);
Number printReqID = (Number)specRow.getAttribute("PrintRequestId");
String PrintState = specRow.getAttribute("PrintState").toString();
if (PrintState.equalsIgnoreCase("PRINTED")) {
System.out.println("cann't delete");
FacesContext fctx = FacesContext.getCurrentInstance();
FacesMessage message =
new FacesMessage("Cann't Delete the selected row:" + printReqID);
message.setSeverity(FacesMessage.SEVERITY_ERROR);
fctx.addMessage(null, message);
} else {
System.out.println("delete");
flag=true;
specRow.remove();
if(flag){
System.out.println("before commit");
commitRows();
Can any one help me....Can any one help me...
i written logic in AM but still i am facing the same issue.
can any one help me, is this is bug or coding issue.
If i am not doing scroll down and trying to delete rows then there is no error.... only error is coming when i scroll down and try to delete.
Method:
public void deleteRec(ActionEvent actionEvent) {
// Add event code here...
RowKeySet rowKeySet = (RowKeySet)this.embossTB.getSelectedRowKeys();
CollectionModel cm = (CollectionModel)this.embossTB.getValue();
List<Row> rowsToDelete = new ArrayList<Row>();
for (Object facesTreeRowKey : rowKeySet) {
cm.setRowKey(facesTreeRowKey);
JUCtrlHierNodeBinding rowData = (JUCtrlHierNodeBinding)cm.getRowData();
Number printReqID = (Number)rowData.getAttribute("PrintRequestId");
String PrintState=rowData.getAttribute("PrintState").toString();
if (PrintState.equalsIgnoreCase("PRINTED")){
System.out.println("cann't delete");
FacesContext fctx = FacesContext.getCurrentInstance();
FacesMessage message =
new FacesMessage("Cann't Delete the selected row:" + printReqID);
message.setSeverity(FacesMessage.SEVERITY_ERROR);
fctx.addMessage(null, message);
} else{
System.out.println("delete");
Row row1 = rowData.getRow();
rowsToDelete.add(row1);
// deletePrintRecords(printReqID);
for (Row row : rowsToDelete){
System.out.println("inside deleting rows");
row.remove();
//commitRows();
System.out.println("After commit from am");
public void commitRows(){
// System.out.println("commit");
DCIteratorBinding embossIter =
ADFUtils.findIterator("XxwfsAvcardEmbossInterfaceVO1Iterator");
ADFUtils.invokeEL("#{bindings.Commit.execute}");
embossIter.getViewObject().executeQuery();
AdfFacesContext.getCurrentInstance().addPartialTarget(embossTB);
Edited by: user5802014 on Sep 3, 2010 11:47 AM
Edited by: user5802014 on Sep 3, 2010 1:07 PM -
Delete Duplicate rows in Data Package based on selection
Hello experts,
I have the data coming from Oracle using DB_Connect. The data has duplicate order no. I need to delete the duplicate rows in the data package based selection before updating the data target.
I am thinking of writing this in updaterule start routine. I would greatly appreciate any sample code on selective deletion of data package rows.
Thanks a lot!
SriNagesh,
Thanks for your reply.
Do I need write this in Update Start routine?
Another thing the order number field is coming from source system. Currently we are not mapping/assingning to InfoObject. In other words we are not seding order no to data target.
In my query can I write something like this...
DELETE ADJACENT DUPLICATES FROM DATA_PACKAGE COMPARING DATA_Package-OrderNo
Thanks a lot!
Sri -
Problem in Creating new row & inserting data using CreateInsert and Commit
Hello All,
I have created a page there are few input text and i want to insert the data into a database table. I have created an Application Module I am using CreateInsert and Commit operation but there is one problem.
At first it created a row in database after that it is not creating the new row instead it is updating the same row with the new values.
In bindings of my jspx page I have created two binding for action (1) CreateInsert for the VO of that Application Module (2) Commit operation of that Application Module.
Here is the code snippet of my application:
BindingContainer bindings = getBindings();
OperationBinding operationBinding = bindings.getOperationBinding("CreateInsert");
Object result = operationBinding.execute();
*if (!operationBinding.getErrors().isEmpty()) {*
return null;
OperationBinding operationBinding1 = bindings.getOperationBinding("Commit");
Object result1 = operationBinding1.execute();
*if (!operationBinding1.getErrors().isEmpty()) {*
return null;
I have tried using Execute+Commit and Insert+Commit case also in every case it is updating the same row and not inserting a new row.
Is there anything I am missing?
Please Help.hi user,
i dono. why are trying with codes. adf provides zero lines codes.
a wonderful drag and drop functionality provide by the framework.
while double click the button the codes are registered in your bean
public String cb6_action() {
BindingContainer bindings = getBindings();
OperationBinding operationBinding = bindings.getOperationBinding("CreateInsert");
Object result = operationBinding.execute();
if (!operationBinding.getErrors().isEmpty()) {
return null;
return null;
public String cb8_action() {
BindingContainer bindings = getBindings();
OperationBinding operationBinding = bindings.getOperationBinding("Commit");
Object result = operationBinding.execute();
if (!operationBinding.getErrors().isEmpty()) {
return null;
return null;
public String cb7_action() {
BindingContainer bindings = getBindings();
OperationBinding operationBinding = bindings.getOperationBinding("Delete");
Object result = operationBinding.execute();
if (!operationBinding.getErrors().isEmpty()) {
return null;
return null;
public String cb14_action() {
BindingContainer bindings = getBindings();
OperationBinding operationBinding =
bindings.getOperationBinding("Delete4"); // some different here. after deleting usually do commit
OperationBinding operationBinding1 =
bindings.getOperationBinding("Commit"); // so here commit operation.
Object result = operationBinding.execute();
Object result1 = operationBinding1.execute();
if (!operationBinding.getErrors().isEmpty()) {
return null;
if (!operationBinding1.getErrors().isEmpty()) {
//add error handling here
return null;
return null;
}if am not understud correctly. please some more explanation need. -
How can I delete a row in access using the database toolkit?
I want to delete just one row of a access table using the database toolkit. Can it be done and if so How?
Take a look at page A-1 of the database connetivity manual. It has information on making a sql query that will delete. You will need to use this command with the dbtools execute query function. Look in the shipping examples for an example with this function.
-
while replaying ajax truclient script in loadrunner 11.0, getting error "this connection is untrust" page in 40th step. Add this exeception permanently check box is disable when i got the exeception certificate file. i tried with by deleting cert8.db file in loadrunner ajax truclient profile but still same result.
can any one guide me to resolve this issue...Is that content loaded in an iframe?
You can check that via the right-click context menu to see if there is a "This Frame" item.<br />
If that is the case then try top open the frame in a new tab or otherwise check the Technical Details of the error message. -
How to return the correct row of data using diffferent conditions?
I am having some problems with an sql query and I hope someone can help please?
The data I am using is customers with multiple transactions. If a customer contains one transaction where the transaction type = 'W' then I need to set the output value to be transaction.ValueA. If the customer does not contain any transactions where the transaction type is 'W' then I need to set the output value to be
the most recent transaction.ValueB where transaction.transaction_date <= customer.cust_mod_date.
Here is an example of the data. For each test customer 10 and 20 I have put a star against the value I want to return
CUSTOMER_ID CUST_MOD_DATE TX_DATE TX_TYPE TX_VALUEA TX_VALUEB
10 15/07/2009 16/07/2009 A 110 95
10 15/07/2009 14/07/2009 A 100 90(*)
10 15/07/2009 13/07/2009 A 90 10
10 15/07/2009 12/07/2009 A 80 5
20 15/07/2009 15/07/2009 A 60 10
20 15/07/2009 14/07/2009 W 50(*) 20
20 15/07/2009 13/07/2009 A 40 30
ie
CREATE TABLE
TMP_CUSTOMER (CUSTOMER_ID NUMBER, CUST_MOD_DATE DATE);
insert into tmp_customer
values(10, to_date('15/07/2009','dd/mm/yyyy'));
insert into tmp_customer
values(20, to_date('15/07/2009','dd/mm/yyyy'));
CREATE TABLE
TMP_TRANSACTION (TX_ID NUMBER, CUSTOMER_ID NUMBER, TX_DATE DATE, TX_TYPE VARCHAR2(1), TX_VALUEA NUMBER, TX_VALUEB NUMBER);
INSERT INTO TMP_TRANSACTION
VALUES (1,10, to_date('16/07/2009','dd/mm/yyyy'),'A',110,95);
INSERT INTO TMP_TRANSACTION
VALUES (2,10, to_date('14/07/2009','dd/mm/yyyy'),'A',100,90);
INSERT INTO TMP_TRANSACTION
VALUES (3,10, to_date('13/07/2009','dd/mm/yyyy'),'A',90,10);
INSERT INTO TMP_TRANSACTION
VALUES (4,10, to_date('12/07/2009','dd/mm/yyyy'),'A',80,5);
INSERT INTO TMP_TRANSACTION
VALUES (5,20, to_date('15/07/2009','dd/mm/yyyy'),'A',60,10);
INSERT INTO TMP_TRANSACTION
VALUES (6,20, to_date('14/07/2009','dd/mm/yyyy'),'W',50,20);
INSERT INTO TMP_TRANSACTION
VALUES (7,20, to_date('13/07/2009','dd/mm/yyyy'),'A',40,30);
The query I have so far is
(SELECT CUSTOMER_ID, CUST_MOD_DATE, TX_DATE, TYPE_FLAG, TX_VALUEA, TX_VALUEB, RN
FROM (SELECT CUST.CUSTOMER_ID, CUST.CUST_MOD_DATE,TRANS.TX_DATE, TRANS.TYPE_FLAG, TRANS.TX_VALUEA,TRANS.TX_VALUEB,
ROW_NUMBER() OVER (partition BY TRANS.CUSTOMER_ID ORDER BY TRANS.TX_DATE DESC) RN
FROM TMP_CUSTOMER CUST,
--- Return all transactions creating a type_flag field where Y = type W, else N ---
SELECT CUST.CUSTOMER_ID, TX.TX_DATE, TX.TX_VALUEA, TX.TX_VALUEB, CUST.CUST_MOD_DATE, TX.TX_TYPE,
CASE WHEN NVL(TX.TX_TYPE,'0') <> 'W' THEN 'N'
WHEN NVL(TX.TX_TYPE,'0') = 'W' THEN 'Y'
ELSE 'N'
END AS TYPE_FLAG
FROM TMP_TRANSACTION TX, TMP_CUSTOMER CUST
WHERE TX.CUSTOMER_ID = CUST.CUSTOMER_ID
AND CUST.CUSTOMER_ID in
'10','20'
) TRANS
WHERE CUST.CUSTOMER_ID = TRANS.CUSTOMER_ID
--AND TRANS.TX_DATE <= CUST.CUST_MOD_DATE
AND CUST.CUSTOMER_ID in
('10','20'
Can anyone please help with how I extract the record I am looking for
ie customer 10 has amount 90
customer 20 has amount 50.
Thanks :-)
GBSQL> select c_id
2 , cust_mod_date
3 , tx_date
4 , tx_type
5 , tx_valuea
6 , tx_valueb
7 from ( select c.customer_id c_id
8 , c.cust_mod_date
9 , t.tx_date
10 , t.tx_type
11 , t.tx_valuea
12 , t.tx_valueb
13 , row_number() over (partition by c.customer_id order by t.customer_id, t.tx_date desc) rn
14 from tmp_customer c
15 , tmp_transaction t
16 where t.customer_id = c.customer_id
17 and t.tx_date <= c.cust_mod_date
18 )
19 where case
20 when tx_type = 'W' then 1
21 when rn = 1
22 and not exists ( select null
23 from tmp_transaction t2
24 where t2.customer_id = c_id
25 and t2.tx_type = 'W'
26 )
27 then 1
28 end = 1;
C_ID CUST_MOD_ TX_DATE T TX_VALUEA TX_VALUEB
10 15-JUL-09 14-JUL-09 A 100 90
20 15-JUL-09 14-JUL-09 W 50 20
2 rows selected. -
Updating one row of data using CMP
Hi,
How should I update a single row mapped with a CMP persitence, should I write a differetnt method for update , pl clarify in detail.Hi,
How should I update a single row mapped with a CMP
P persitence, should I write a differetnt method for
update , pl clarify in detail.Hi,
You can just find that particular Row using the findByPrimaryKey method the entity.
This method actually returns the Remote Interface for the Entity which contains taht particular row of record.
Use The setters of the Remote interface to update your existing Row. -
How to get two rows of data using GUI_DOWNLOAD
Hi i am using GUI_DOWNLOAD i am downloading data into excel succesfully.....
i am getting data as
Pernr Fname Lname
1000 F1000 L1000
2000 F2000 L2000
requirement
is to add one more field on the top of text as what is the run date .
is it possible using GUI_DOWNLOAD? or need to use oops/OLE only one ?
RUNDATE: 15/05/2009
Pernr Fname Lname
1000 F1000 L1000
2000 F2000 L2000
Regards
sasHi,
check the below code, it's working as per your requirement. For the second call of FM use
append = 'X'.
DATA: it_date TYPE TABLE OF char30, "For downloading Rundate
wa_date LIKE LINE OF it_date.
CONCATENATE 'Rundate: ' sy-datum+6(2) '.' sy-datum+4(2) '.'
sy-datum+0(4) INTO wa_date.
APPEND wa_date TO it_date.
"Download the Rundate first
CALL FUNCTION 'GUI_DOWNLOAD'
EXPORTING
filename = 'D:\1.xls'
filetype = 'DAT'
write_field_separator = 'X'
TABLES
data_tab = it_date.
"Now download your data tab with header with the append parameter as X
CALL FUNCTION 'GUI_DOWNLOAD'
EXPORTING
filename = 'D:\1.xls'
filetype = 'DAT'
append = 'X'
write_field_separator = 'X'
TABLES
data_tab = it_tab
fieldnames = it_header.
Hope this helps you.
Regards,
Manoj Kumar P
Edited by: Manoj Kumar on May 15, 2009 8:46 AM -
I am trying to delete a row from a JTable whenever the button on the last column is pressed. I know to do this, I can use the removeRow(int) method of the tableModel. But the odd thing is when I try to get a handle to the TableModel from the JTable to use that function, i.e. table.getModel().removeRow(int) it doesn't work. But if I explicitly pass in the tableModel into my class it does work. Here's the code below:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.UIManager;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableCellEditor;
import javax.swing.AbstractCellEditor;
import javax.swing.table.DefaultTableModel;
public class tester4 extends JFrame
protected final int BUTTON_COL = 2;
private TableCellRenderer defaultRenderer;
private TableCellEditor defaultEditor;
private JTable workingTable;
private String[] transactionCols = {"Qty", "Product", "Cancel"};
private Object[][] data = {{5, "prod1", "Cancel"},
{6, "prod2", "Cancel"},
{7, "prod3", "Cancel"}};
public tester4()
workingTable = new JTable(tableModel);
workingTable.setName("Working Table");
defaultRenderer = workingTable.getDefaultRenderer(JButton.class);
defaultEditor = workingTable.getDefaultEditor(Object.class);
StatusTableRenderer testRenderer = new StatusTableRenderer(defaultRenderer, defaultEditor, workingTable, tableModel);
workingTable.setDefaultRenderer(Object.class, testRenderer);
workingTable.setDefaultEditor(Object.class, testRenderer);
JScrollPane scrollPane = new JScrollPane( workingTable );
getContentPane().add( scrollPane );
private DefaultTableModel tableModel = new DefaultTableModel(data, transactionCols){
// Only allow button column to be editable, if there is an actual
// button in that row
public boolean isCellEditable(int row, int col){
return (col == BUTTON_COL && data[row][col] != "") ? true : false;
// Overriden getColumnClass method that will return the object
// class type of the first instance of the data type otherwise
// returns the Object.class
public Class getColumnClass(int column){
for (int row = 0; row < getRowCount(); row++){
Object o = getValueAt(row, column);
if (o != null){ return o.getClass(); }
return Object.class;
public static void main(String[] args)
tester4 frame = new tester4();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
public class StatusTableRenderer extends AbstractCellEditor
implements TableCellRenderer,
TableCellEditor,
ActionListener{
private TableCellRenderer defaultRenderer;
private TableCellEditor defaultEditor;
private JButton cancelButton;
private JButton editButton;
private String text;
private int buttonColumn;
private int selectedRow;
private JTable table;
private DefaultTableModel tableModel;
public StatusTableRenderer(TableCellRenderer renderer,
TableCellEditor editor,
JTable table,
DefaultTableModel tableModel){
defaultRenderer = renderer;
defaultEditor = editor;
this.table = table;
this.tableModel = tableModel;
buttonColumn = table.getColumnCount() - 1;
cancelButton = new JButton();
editButton = new JButton();
editButton.setFocusPainted(true);
editButton.addActionListener(this);
public StatusTableRenderer(TableCellRenderer renderer,
TableCellEditor editor,
JTable table,
DefaultTableModel tableModel,
int _buttonColumn){
this(renderer, editor, table, tableModel);
buttonColumn = _buttonColumn;
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (column == buttonColumn){
if (hasFocus){
cancelButton.setForeground(table.getForeground());
cancelButton.setBackground(UIManager.getColor("Button.background"));
else if (isSelected){
cancelButton.setForeground(table.getSelectionForeground());
cancelButton.setBackground(table.getSelectionBackground());
else{
cancelButton.setForeground(table.getForeground());
cancelButton.setBackground(UIManager.getColor("Button.background"));
cancelButton.setText( (value == null) ? "" : value.toString() );
return cancelButton;
return defaultRenderer.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column){
if (column == buttonColumn){
text = ((value == null) ? "": value.toString());
editButton.setText(text);
selectedRow = row;
return editButton;
return defaultEditor.getTableCellEditorComponent(
table, value, isSelected, row, column);
public Object getCellEditorValue()
return text;
public void actionPerformed(ActionEvent e)
fireEditingStopped();
// This works
tableModel.removeRow(selectedRow);
// This does not work
// table.getModel().removeRow(selectedRow);
}Take a look at the actionPerfformed method. One way of doing it works, one doesn't. Just trying to understand why me getting a handle to the tableModel through the table doesn't work.
Message was edited by:
deadseasquirrelsIt gives me a run-time error Well then your question should be "why do I get this run-time error" and then you would quote the error. Be more descriptive. "It doesn't work" is not descriptive.
table.getModel().removeRow(selectedRow);I don't use JDK1.5 either. But if you are saying that the above line compiles cleanly with JDK1.5 (because of the auto-boxing feature, or whatever its called), then I see no reason why the code wouldn't work since it recognizes the class as a DefaultTableModel.
Presumably you commented out the other line so you don't try to delete the row twice. Otherwise you might be getting a indexing error. -
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
public class ContractorTableModel extends 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.
public int getColumnCount() {
return this.headerNames.length;
* Returns the number of rows in the table.
* @return An integer indicating the number of rows in the table.
public int 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.
public void 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.
public boolean isCellEditable(int row, int column) {
return false;
* 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
public void 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.
public void 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.
public void deleteContractorRecord(int recNo) {
contractorRecords.remove(recNo - 1);
fireTableRowsDeleted(recNo -1, recNo - 1);
}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. -
Transporting Deleted Rows of Data
Hello! I have run into a slight issue I am hoping someone can help me with! I created a table in our development client and added some data to the table using SE16N. I created a transport for the data and used SCC1 on the test client to transport the data over. It turned out I needed to make some changes to the data in my table which included deleting some rows of data as well as adding new rows of data. I did this and saved under the same transport number. I pulled the data over using SCC1 again and the old rows that I had deleted in the development client remained in the test client! Any ideas on how to get these old rows out of the test client?
Thank youWendy,
If you have created the table then you can always create a maintenance view for the table in generate table maintenance modules using table maintenance generator. To go to table maintenance generator select Utilities --> Table Maintenance Generator. You can also use the transaction SE54 for that. Once you have done this and you can maintain the table using SM30 in any client you want.
Gajendra -
Error while deleting a row in entity
Hi
I am facing a problem while trying to delete a row from a entity.
Below is the scenario where i am facinmg a problrm.
I have a ViewObject which has attributes from two entity and on e transient variable.
in the RowImpl java class for the above Viewobject i changes the getter method of the transient variable to some text.
I display all the Viewobject as a table in the UI.
When a user selects a row and press delete method.
I get a id(one of the attribute from the Viewobject) from the selected row and remove the row from the Entity.
When i try to commit the changes i am getting the below error
Another user has changed the row with primary key oracle.jbo.Key [742]. (Another user has changed the row with primary key {0}.)
Can any one please help me in this
Thanks
Ranjithcheck {message:id=9271952}
Maybe you are looking for
-
How to use Sql Loader in Unix Environmant
Hi All, Can anyone explain me please how to use sql Loader in unix environment. Actually i have one control file i want to run that file in Unix how can i achive please explain me Thank's
-
Itunes Automatically opening ... pls help
Iam Using iTunes (11.0.1 on mac osc 10.8.2) and iTunes started to open automatically since yesterday ... this is happening even after deleting itunes pref. files and itunes helper preference files
-
What's the normal fan speed?
Hello, my fans have always been around 2000 rpm with both tiger and leopord, so I am wondering what is the normal range for fan speed when the computer is not running anything heavy.
-
Read raw files for nikon d5200 camera
I have given up using raw files for several Nikon bodies such as the d5200 on Adobe software since Adobe no longer supports these files even with the updates that are supposed to support these files. I can open the raw files fine using Nikon softwar
-
I just installed Photoshop but when I try and open it, I keep getting the error, "To open "Adobe Photoshop CC," you need to install a Java SE 6 runtime, but you are not connected to the Internet." However, I am connected to the internet, and I have