How to delete a row from JTable ?

Hi,

I want to delete a row from JTable. I am using DefaultTableModel class.

Problem is : every time when i try to delete the row, it is deletingfinal/last row. before deleting the row i am printing the 'row' value, it's displaying the correct row number, i.e., which i selected.

I am totally confused how it is deleting the last row.

my snippet :

tablemodel.removeRow(row);

please suggest where i am going wrong or snippets in this regard.

Regards,

Ravi

[536 byte] By [rkrgarlapatia] at [2007-11-27 4:32:20]
# 1
// Remove the last row tableModel.removeRow(tableModel.getRowCount()-1);
java_2006a at 2007-7-12 9:41:58 > top of Java-index,Desktop,Core GUI APIs...
# 2

I can't guess what you're doing wrong.

If you want further help post a Short, Self Contained, Compilable and Executable, Example Program ([url http://homepage1.nifty.com/algafield/sscce.html]SSCCE[/url]) that demonstrates the problem.

And don't forget to use [url http://forum.java.sun.com/help.jspa?sec=formatting]code formatting[/url] when posting code.

Rodney_McKaya at 2007-7-12 9:41:58 > top of Java-index,Desktop,Core GUI APIs...
# 3

Thanks for your reply.

the snippet that you provided deletes the last row every time, that is not what i want.

suppose i have 10 rows in a table, when i try to delete 5th row, 10th row is getting deleted. even if i delete the 1st row, it's deleting the last row. This is not what i want to happen.

JTable source = (JTable)e.getSource(); // e is an object of MouseEvent.

int row_number = source.rowAtPoint( e.getPoint() );

System.out.println(row_number); // it is displayng the correct row number, i.e., the row number which i selected.

tableModel.removeRow(row_number); // but this is deleting the last row.

what's wrong with tableModel.removeRow(row_number) code.

any suggestion plz.

rkrgarlapatia at 2007-7-12 9:41:58 > top of Java-index,Desktop,Core GUI APIs...
# 4

I can't see why your code is causing a problem.

DefaultTableModel stores your table data in a Vector object, which can be retrieved by DefaultTableModel.getDataVector().

When you call removeRow(int), all it does is call removeElementAt(int) on that vector. So maybe the vector is the cause of the problem, not the table model.

Try using tablemodel.getDataVector().removeRow(int), to see if this has the same effect. If it does, then the problem is with the vector itself.

clairec666a at 2007-7-12 9:41:58 > top of Java-index,Desktop,Core GUI APIs...
# 5

Thanks you clairec666,

>Try using tablemodel.getDataVector().removeRow(int),

tablemodel.getDataVector() --> returns Vector object.

removeRow(int) method doesn't exists in Vector class.

I am getting compilation error :

symbol : method removeRow (int)

location: class java.util.Vector

rkrgarlapatia at 2007-7-12 9:41:58 > top of Java-index,Desktop,Core GUI APIs...
# 6
> what's wrong with tableModel.removeRow(row_number) code.Nothing. It works fine. There is something wrong with your code and since you haven't posted your SSCCE as previously asked I guess we'll never find out whats wrong.
camickra at 2007-7-12 9:41:58 > top of Java-index,Desktop,Core GUI APIs...
# 7

import java.awt.*;

import java.awt.event.*;

import java.util.*;

import javax.swing.*;

import javax.swing.event.*;

import javax.swing.table.*;

import java.util.*;

import com.mqmonitor.mq.beans.MQMChannel;

public class TableSorterColumn extends JPanel {

private boolean DEBUG = false;

DefaultTableModel tablemodel = null;

String qmname;

public TableSorterColumn(String[] vec,Object[][] channelslist)

{

super(new BorderLayout());

tableSorterColumn(vec,channelslist);

}

public void tableSorterColumn(String[] vec,Object[][] channelslist) {

JFrame frame = new JFrame("ChannelsTableSorterColumn");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

if(channelslist != null)

{

System.out.println("just before calling MyTableModel() constructor");

tablemodel = new MyTableModel(vec,channelslist);

//sorter = new TableSorter(tablemodel);

}

else

return;

final JTable table = new JTable(tablemodel)

{

public boolean isCellEditable(int row,int column)

{

return false;

}

};

table.addMouseListener( new MouseAdapter()

{

public void mouseReleased(MouseEvent e)

{

//if ( SwingUtilities.isRightMouseButton(e) )

if (e.isPopupTrigger())

{

JTable source = (JTable)e.getSource();

final int row = source.rowAtPoint( e.getPoint() );

int column = source.columnAtPoint( e.getPoint() );

//final int sizeoftable = source.getRowCount() ;

System.out.println(row +" --> " +column);

source.changeSelection(row, column, false, false);

JMenu writemessage = null;

JPopupMenu popup = new JPopupMenu();

ActionListener menuListener = new ActionListener()

{

public void actionPerformed(ActionEvent event)

{

if(event.getActionCommand().equals("Delete Channel"))

{

System.out.println("row number is :::: "+row);

tablemodel.removeRow(row);

}

}

};

JMenuItem item,deletech;

popup.add(deletech = new JMenuItem("Delete Channel") );

deletech.addActionListener(menuListener);

popup.add( item = new JMenuItem("Refresh Channel") );

item.addActionListener(menuListener);

popup.show(e.getComponent(), e.getX(), e.getY());

}

}

});

table.getTableHeader().setToolTipText("Click to sort data");

table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );

JScrollPane scrollPane = new JScrollPane(table);

add(scrollPane);

}

class MyTableModel extends DefaultTableModel {

Object channelslist;

String[] vec;

String[] channelcolumnNames;

Object[][] data;

MyTableModel(String[] vec, Object[][] channelslist)

{

//super(vec,channelslist);

System.out.println("inside of MyTableModel() constructor");

this.channelslist = channelslist;

this.vec = vec;

this.channelcolumnNames = vec;

MQMChannel mqChannel = null;

int i = 0;

data = channelslist;

}

public String getColumnName(int col) {

return channelcolumnNames[col];

}

public Object getValueAt(int row, int col) {

return data[row][col];

}

public Class getColumnClass(int c) {

return getValueAt(0, c).getClass();

}

public boolean isCellEditable(int row, int col) {

//Note that the data/cell address is constant,

//no matter where the cell appears onscreen.

if (col < 2) {

return false;

} else {

return true;

}

}

public void setValueAt(Object value, int row, int col) {

data[row][col] = value;

fireTableCellUpdated(row, col);

if (DEBUG) {

//System.out.println("New value of data:");

//printDebugData();

}

}

}

private static void createAndShowGUI() {

//Create and set up the window.

String[] columnNames = {"First Name","Last Name","Sport","# of Years","Vegetarian"};

Object[][] data = {

{"Mary", "Campione","Snowboarding", new Integer(5), new Boolean(false)},

{"Alison", "Huml","Rowing", new Integer(3), new Boolean(true)},

{"Kathy", "Walrath","Knitting", new Integer(2), new Boolean(false)},

{"Sharon", "Zakhour","Speed reading", new Integer(20), new Boolean(true)},

{"Philip", "Milne","Pool", new Integer(10), new Boolean(false)}

};

//Create and set up the content pane.

JFrame frame = new JFrame("TableSorterColumn");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create and set up the content pane.

TableSorterColumn newContentPane = new TableSorterColumn(columnNames,data);

newContentPane.setOpaque(true); //content panes must be opaque

frame.setContentPane(newContentPane);

//Display the window.

frame.pack();

frame.setVisible(true);

}

public static void main(String[] args) {

javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {

createAndShowGUI();

}

});

}

}

This is my snippet, i am working on SSCCE. that was huge file, finally i could make this program, I am unable to display the table on Frame.

If we walk through the code, we can find bold line where i am unable to delete my desired row.

rkrgarlapatia at 2007-7-12 9:41:58 > top of Java-index,Desktop,Core GUI APIs...
# 8

Not a SSCCE. You question is about deletintg a row from a table. You don't need a custom TableModel for this. First you prove the method works with the standard classes. Then if you need to customize a class you know what changes you have made and if the code stops working you know where to look for the problem.

Also, the code is not formatted, so I'm not going to waste time trying to read it.

camickra at 2007-7-12 9:41:58 > top of Java-index,Desktop,Core GUI APIs...
# 9

Hi camickr,

Thanks for your reply, below was your post to one of my queries. So i am following the same steps which u have posted for removing a row from JTable.

http://forum.java.sun.com/thread.jspa?threadID=5170244&messageID=9653926#9653926

Requesting to correct me if i am wrong.

>First you prove the method works with the standard classes.

How to delete a row using Standard classes ?

>You don't need a custom TableModel for this

But we can delete a row from table using DefaultTableModel, how it can be achived with out using TableModel.

plz help in this regard.

rkrgarlapatia at 2007-7-12 9:41:58 > top of Java-index,Desktop,Core GUI APIs...
# 10

> How to delete a row using Standard classes ?

Use the DefaultTableModel, it already has a removeRow(...) method with the appropriate code.

> how it can be achived with out using TableModel.

You have to use a TableModel. You can always look at the source code from the DefaultTableModel to see how it is done.

Basically you need to remove the "data" from your data structure. Then you need to notifiy the table that the data has changed so the table can repaint itself correctly. This is done by using the fireTableRowsDeleted(...) method.

camickra at 2007-7-12 9:41:58 > top of Java-index,Desktop,Core GUI APIs...