Mike_Toth
asked on
Trying to delete a row from JTable using Abstract Table Model
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
Sorry if this looks a bit scattered, I had to cut/paste from a Linux NotePad type program
Here are snippets of my main class and Abstract Table Model :
Main Class
Table definition and mouse listener:
usermodel = new DataFileTableModel("UserCt l.dat") ;
userTable = new JTable();
userTable.setModel(usermod el);
userTable.createDefaultCol umnsFromMo del();
userTable.addMouseListener (new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
upoint = evt.getPoint();
rowToBeDeleted = userTable.rowAtPoint(upoin t);
}
});
Menu Selection which calls the deleteRow Method in the model:
deleteitem = new JMenuItem("Delete Row",'D');
editmenu.add(deleteitem) ;
deleteitem.addActionListen er(new ActionListener() {
public void actionPerformed(ActionEven t e) {
int delresp = JOptionPane.showConfirmDia log(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(rowToB eDeleted);
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.readLin e(), "|");
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.nextTo ken());
}
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.elemen tAt(column Index);
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())+columnIn dex) ;
fireTableCellUpdated(rowIn dex, columnIndex);
}
public void addRow(Object[] aRow) {
for (int i=0; i < aRow.length; i++)
data.add(aRow[i]);
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("colCou nt = " + colCount);
System.out.println("index = " + index) ;
for (int d = index; d <= colCount; d++)
data.remove(d) ;
fireTableRowsDeleted(rowNo ,rowNo) ;
}
}
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
Sorry if this looks a bit scattered, I had to cut/paste from a Linux NotePad type program
Here are snippets of my main class and Abstract Table Model :
Main Class
Table definition and mouse listener:
usermodel = new DataFileTableModel("UserCt
userTable = new JTable();
userTable.setModel(usermod
userTable.createDefaultCol
userTable.addMouseListener
public void mouseClicked(MouseEvent evt) {
upoint = evt.getPoint();
rowToBeDeleted = userTable.rowAtPoint(upoin
}
});
Menu Selection which calls the deleteRow Method in the model:
deleteitem = new JMenuItem("Delete Row",'D');
editmenu.add(deleteitem) ;
deleteitem.addActionListen
public void actionPerformed(ActionEven
int delresp = JOptionPane.showConfirmDia
switch(delresp) {
case JOptionPane.NO_OPTION:
return;
case JOptionPane.YES_OPTION:
switch (tabnum)
{
case 0:
usermodel.deleteRow(rowToB
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.readLin
while(st1.hasMoreTokens())
columnNames.addElement(st1
// extract data
while ((aLine = br.readLine()) != null) {
StringTokenizer st2 =
new StringTokenizer(aLine, "|");
while(st2.hasMoreTokens())
data.addElement(st2.nextTo
}
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.elemen
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())+columnIn
fireTableCellUpdated(rowIn
}
public void addRow(Object[] aRow) {
for (int i=0; i < aRow.length; i++)
data.add(aRow[i]);
int size = getRowCount();
fireTableRowsInserted(size
}
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("colCou
System.out.println("index = " + index) ;
for (int d = index; d <= colCount; d++)
data.remove(d) ;
fireTableRowsDeleted(rowNo
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class SimpleTable extends JFrame {
private SmartTable table;
private Actions actions;
public SimpleTable() { init(); }
private void init() {
getContentPane().setLayout (new BorderLayout());
setSize(600, 300);
setLocation(300, 100);
table = new SmartTable();
actions = new Actions();
getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
getContentPane().add(actio ns, BorderLayout.SOUTH);
setVisible(true);
}
class Actions extends JPanel {
JButton add = new JButton("Add");
JButton remove = new JButton("Remove");
JButton selected = new JButton("Dump selected");
JButton dump = new JButton("Dump content to console");
public Actions() {
setLayout(new FlowLayout());
setListeners();
add(add);
add(remove);
add(selected);
add(dump);
}
public DBObject createDBObject() {
DBObject dbo = new DBObject();
int curent = SimpleTable.this.table.get RowCount() ;
dbo.f1 = "DBO " + curent + " field 1";dbo.f2 = "DBO " + curent + " field 2";
dbo.f3 = "DBO " + curent + " field 3";dbo.f4 = "DBO " + curent + " field 4";
dbo.f5 = "DBO " + curent + " field 5";dbo.f6 = "DBO " + curent + " field 6";
dbo.f7 = "DBO " + curent + " field 7";dbo.f8 = "DBO " + curent + " field 8";
return(dbo);
}
protected void setListeners() {
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEven t ae) {
SimpleTable.this.table.add DBObject(c reateDBObj ect());
}
});
remove.addActionListener(n ew ActionListener() {
public void actionPerformed(ActionEven t ae) {
try {
int selected = SimpleTable.this.table.get SelectedRo w();
SimpleTable.this.table.rem oveDBObjec tAt(select ed);
SimpleTable.this.table.set SelectedRo w(selected );
} catch(Exception e) {}
}
});
selected.addActionListener (new ActionListener() {
public void actionPerformed(ActionEven t ae) {
try {
int row = SimpleTable.this.table.get SelectedRo w();
int col = SimpleTable.this.table.get SelectedCo lumn();
System.out.println("Select ed : [" + row + ", " + col + "]");
} catch(Exception e) {}
}
});
dump.addActionListener(new ActionListener() {
public void actionPerformed(ActionEven t ae) {
Vector objs = SimpleTable.this.table.get DBObjects( );
for(int i = 0; i < objs.size(); i++) {
DBObject o = (DBObject)objs.elementAt(i );
System.out.println("DBObje ct " + i + ": " + o.f1 + ", " + o.f2 + ", " + o.f3 +
", " + o.f4 + ", " + o.f5 + ", " + o.f6 + ", " + o.f7 + ", " + o.f8);
}
}
});
}
}
class SmartTable extends JTable {
SmartTableModel model;
public SmartTable() {
model = new SmartTableModel();
createColumns();
setModel(model);
setForeground(Color.red);
setBackground(new Color(255, 239, 185));
setGridColor(Color.orange) ;
setSelectionMode(ListSelec tionModel. SINGLE_SEL ECTION);
}
protected void createColumns() {
for(int i = 0; i<model.getColumnCount(); i++) {
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer() ;
renderer.setHorizontalAlig nment(mode l.cols[i]. alignment) ;
TableColumn column = new TableColumn(i, model.cols[i].width, renderer, null);
addColumn(column);
}
}
public void addDBObject(DBObject object) { model.addDBObject(object); }
public void addDBObjects(Vector objects) { model.addData(objects);}
public void removeDBObjectAt(int idx) { model.removeDBObjectAt(idx );}
public DBObject getDBObject(int row) { return(model.getDBObject(r ow)); }
public Vector getDBObjects() { return(model.getDBObjects( )); }
protected void setSelectedRow(int row) {
if(row < 0)
clearSelection();
else {
clearSelection();
setRowSelectionInterval(ro w, row);
}
}
protected void setSelectedCol(int col) {
if(col < 0)
clearSelection();
else {
clearSelection();
setColumnSelectionInterval (col, col);
}
}
}
class SmartTableModel extends AbstractTableModel {
protected ColumnDescriptor cols[] = {
new ColumnDescriptor("Field1", 40, JLabel.LEFT),
new ColumnDescriptor("Field2", 50, JLabel.LEFT),
new ColumnDescriptor("Field3", 100, JLabel.LEFT),
new ColumnDescriptor("Field4", 60, JLabel.LEFT),
new ColumnDescriptor("Field5", 50, JLabel.LEFT),
new ColumnDescriptor("Field6", 40, JLabel.LEFT),
new ColumnDescriptor("Field7", 40, JLabel.LEFT),
new ColumnDescriptor("Field8", 40, JLabel.LEFT),
};
protected Vector dbObjects;
public SmartTableModel() {
dbObjects = new Vector();
}
public void addData(Vector v) {
dbObjects.removeAllElement s();
for(int i = 0; i<v.size(); i++) {
dbObjects.addElement((DBOb ject) v.elementAt(i));
}
updateObjects();
}
public void addDBObject(DBObject dbo) {
dbObjects.addElement(dbo);
updateObjects();
}
public void removeDBObjectAt(int idx) {
dbObjects.removeElementAt( idx);
updateObjects();
}
public DBObject getDBObject(int row) {
return((DBObject)dbObjects .elementAt (row));
}
public Vector getDBObjects() {
return(dbObjects);
}
protected void updateObjects() {
fireTableDataChanged();
}
public int getColumnCount() { return(cols.length); }
public int getRowCount() { return(dbObjects.size()); }
public String getColumnName(int c) { return(cols[c].name); }
public boolean isCellEditable(int row, int col) { return(true); }
public Object getValueAt(int row, int col) {
if(getRowCount() <= 0)
return "";
if(row<0||row>=getRowCount ())
return "";
DBObject dbo = (DBObject) dbObjects.elementAt(row);
switch(col) {
case 0: return dbo.f1;
case 1: return dbo.f2;
case 2: return dbo.f3;
case 3: return dbo.f4;
case 4: return dbo.f5;
case 5: return dbo.f6;
case 6: return dbo.f7;
case 7: return dbo.f8;
}
return "";
}
}
class ColumnDescriptor {
public String name;
public int width;
public int alignment;
public ColumnDescriptor(String n, int w, int a) {
name = n;
width = w;
alignment = a;
}
}
class DBObject {
public String f1;
public String f2;
public String f3;
public String f4;
public String f5;
public String f6;
public String f7;
public String f8;
}
public static void main(String[] args) {
SimpleTable t = new SimpleTable();
}
}
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class SimpleTable extends JFrame {
private SmartTable table;
private Actions actions;
public SimpleTable() { init(); }
private void init() {
getContentPane().setLayout
setSize(600, 300);
setLocation(300, 100);
table = new SmartTable();
actions = new Actions();
getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
getContentPane().add(actio
setVisible(true);
}
class Actions extends JPanel {
JButton add = new JButton("Add");
JButton remove = new JButton("Remove");
JButton selected = new JButton("Dump selected");
JButton dump = new JButton("Dump content to console");
public Actions() {
setLayout(new FlowLayout());
setListeners();
add(add);
add(remove);
add(selected);
add(dump);
}
public DBObject createDBObject() {
DBObject dbo = new DBObject();
int curent = SimpleTable.this.table.get
dbo.f1 = "DBO " + curent + " field 1";dbo.f2 = "DBO " + curent + " field 2";
dbo.f3 = "DBO " + curent + " field 3";dbo.f4 = "DBO " + curent + " field 4";
dbo.f5 = "DBO " + curent + " field 5";dbo.f6 = "DBO " + curent + " field 6";
dbo.f7 = "DBO " + curent + " field 7";dbo.f8 = "DBO " + curent + " field 8";
return(dbo);
}
protected void setListeners() {
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEven
SimpleTable.this.table.add
}
});
remove.addActionListener(n
public void actionPerformed(ActionEven
try {
int selected = SimpleTable.this.table.get
SimpleTable.this.table.rem
SimpleTable.this.table.set
} catch(Exception e) {}
}
});
selected.addActionListener
public void actionPerformed(ActionEven
try {
int row = SimpleTable.this.table.get
int col = SimpleTable.this.table.get
System.out.println("Select
} catch(Exception e) {}
}
});
dump.addActionListener(new
public void actionPerformed(ActionEven
Vector objs = SimpleTable.this.table.get
for(int i = 0; i < objs.size(); i++) {
DBObject o = (DBObject)objs.elementAt(i
System.out.println("DBObje
", " + o.f4 + ", " + o.f5 + ", " + o.f6 + ", " + o.f7 + ", " + o.f8);
}
}
});
}
}
class SmartTable extends JTable {
SmartTableModel model;
public SmartTable() {
model = new SmartTableModel();
createColumns();
setModel(model);
setForeground(Color.red);
setBackground(new Color(255, 239, 185));
setGridColor(Color.orange)
setSelectionMode(ListSelec
}
protected void createColumns() {
for(int i = 0; i<model.getColumnCount(); i++) {
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer()
renderer.setHorizontalAlig
TableColumn column = new TableColumn(i, model.cols[i].width, renderer, null);
addColumn(column);
}
}
public void addDBObject(DBObject object) { model.addDBObject(object);
public void addDBObjects(Vector objects) { model.addData(objects);}
public void removeDBObjectAt(int idx) { model.removeDBObjectAt(idx
public DBObject getDBObject(int row) { return(model.getDBObject(r
public Vector getDBObjects() { return(model.getDBObjects(
protected void setSelectedRow(int row) {
if(row < 0)
clearSelection();
else {
clearSelection();
setRowSelectionInterval(ro
}
}
protected void setSelectedCol(int col) {
if(col < 0)
clearSelection();
else {
clearSelection();
setColumnSelectionInterval
}
}
}
class SmartTableModel extends AbstractTableModel {
protected ColumnDescriptor cols[] = {
new ColumnDescriptor("Field1",
new ColumnDescriptor("Field2",
new ColumnDescriptor("Field3",
new ColumnDescriptor("Field4",
new ColumnDescriptor("Field5",
new ColumnDescriptor("Field6",
new ColumnDescriptor("Field7",
new ColumnDescriptor("Field8",
};
protected Vector dbObjects;
public SmartTableModel() {
dbObjects = new Vector();
}
public void addData(Vector v) {
dbObjects.removeAllElement
for(int i = 0; i<v.size(); i++) {
dbObjects.addElement((DBOb
}
updateObjects();
}
public void addDBObject(DBObject dbo) {
dbObjects.addElement(dbo);
updateObjects();
}
public void removeDBObjectAt(int idx) {
dbObjects.removeElementAt(
updateObjects();
}
public DBObject getDBObject(int row) {
return((DBObject)dbObjects
}
public Vector getDBObjects() {
return(dbObjects);
}
protected void updateObjects() {
fireTableDataChanged();
}
public int getColumnCount() { return(cols.length); }
public int getRowCount() { return(dbObjects.size()); }
public String getColumnName(int c) { return(cols[c].name); }
public boolean isCellEditable(int row, int col) { return(true); }
public Object getValueAt(int row, int col) {
if(getRowCount() <= 0)
return "";
if(row<0||row>=getRowCount
return "";
DBObject dbo = (DBObject) dbObjects.elementAt(row);
switch(col) {
case 0: return dbo.f1;
case 1: return dbo.f2;
case 2: return dbo.f3;
case 3: return dbo.f4;
case 4: return dbo.f5;
case 5: return dbo.f6;
case 6: return dbo.f7;
case 7: return dbo.f8;
}
return "";
}
}
class ColumnDescriptor {
public String name;
public int width;
public int alignment;
public ColumnDescriptor(String n, int w, int a) {
name = n;
width = w;
alignment = a;
}
}
class DBObject {
public String f1;
public String f2;
public String f3;
public String f4;
public String f5;
public String f6;
public String f7;
public String f8;
}
public static void main(String[] args) {
SimpleTable t = new SimpleTable();
}
}
ASKER