problem with jtable listener
hi,
I am facing problem with JTable listener. I have 2 columns and the result of 2 columns multiplication should be print on 3 column. I have used JTable Listener and in tableChanaged() method I have written code. I got everything but while setting value at spcific row I used setValueAt(..) mehod giving exception .my code is giving below
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.io.*;
public class TestTable extends JFrame implements ActionListener,TableModelListener
{
JTable caltable;
Object[][] rows;
Object[] cols;
JButton calculate;
JButton add;
DefaultTableModel tm;
Integer re;
int r=0;
int l=0;
boolean tabBool;
int columnNo;
int rowNo;
TestTable()
{
Object[] cols={"Price","Quantitiy","result"};
Object[][] rows={{"2","2",""},{"3","5",""}};
tm=new DefaultTableModel(rows,cols);
caltable=new JTable(tm);
JScrollPane tabScroll=new JScrollPane(caltable);
//creating new button for adding new row
add=new JButton("add");
add.addActionListener(this);
//adding listener to cloumn
TableColumnModel colModel=caltable.getColumnModel();
TableColumn colSingle=colModel.getColumn(2);
caltable.setSize(300,300);
calculate=new JButton("CALCULATE");
calculate.addActionListener(this);
getContentPane().setLayout(new FlowLayout());
tm.addTableModelListener(this);
this.getContentPane().add(tabScroll);
this.getContentPane().add(calculate);
this.getContentPane().add(add);
this.setSize(500,500);
this.setVisible(true);
}
public void tableChanged(TableModelEvent te)
{
columnNo=caltable.getSelectedColumn();
rowNo=caltable.getEditingRow();
if((columnNo!=-1)&&(columnNo==1))
{
calculate(rowNo,columnNo);
}
}
public void actionPerformed(ActionEvent e)
{
String button_info=e.getActionCommand();
if(button_info.equals("add"))
{
tm.addRow(new String[] {"", "",""});
}
}
void calculate(int rowNo,int colNo)
{
Object frowone=caltable.getValueAt(rowNo,colNo);
Object frowtwo =caltable.getValueAt(rowNo,colNo);
System.out.println("The value is frowone"+frowone);
System.out.println("The value is frowtwo"+frowtwo);
String t= ((String)frowone);
int l=Integer.parseInt(t);
String j=(String)frowtwo;
int k=Integer.parseInt(j);
System.out.println("The i is"+l+"The j is"+k);
int result=l*k;
re=new Integer(result);
System.out.println("The Result is"+re);
tm.setValueAt(re,rowNo,2);
}
public static void main(String args[])
{
TestTable testTable=new TestTable();
testTable.setSize(500,500);
testTable.setVisible(true);
}
}
if remove tm.setValueAt(...) Its giving result at command prompt .
Please try to rectify where I did mistake..
Message was edited by:
harishspi

