deepas
asked on
access textfield outside Jtable
Hi
I have a table for which I maintain a cumulative total for one
of the columns. I'd like to know how to set a textfield outside the jtable to the value of this total.
Regards
Deepa
I have a table for which I maintain a cumulative total for one
of the columns. I'd like to know how to set a textfield outside the jtable to the value of this total.
Regards
Deepa
what about tf.setText((String)table.g etValueAt( row,column )) ?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
jsridhar: can u post comments?
ASKER
the textfield is in a different pane from the table.When I try to settext for the text field I get runtime errors. I've got the total, I just need to display it.
post ur code
ASKER
Here's the code. I've commented out the settext portion.
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.Abstract TableModel ;
import java.awt.*;
import java.util.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.text.*;
import javax.swing.DefaultCellEdi tor;
class DecimalField extends JTextField {
private NumberFormat format;
public DecimalField(double value, int columns, NumberFormat f) {
super(columns);
format = f;
setValue(value);
}
public double getValue() {
double retVal = 0.0;
try {
retVal = format.parse(getText()).do ubleValue( );
} catch (ParseException e) {
// This should never happen because insertString allows
// only properly formatted data to get in the field.
Toolkit.getDefaultToolkit( ).beep();
System.err.println("getVal ue: could not parse: " + getText());
}
return retVal;
}
public void setValue(double value) {
setText(format.format(valu e));
}
}
class rowrecord
{
int serial;
String site,item,um,ppu,discount;
Double np = new Double(0.0);
public rowrecord(int serial)
{
this.serial = serial;
this.site = " ";
this.item = " ";
this.um = " ";
this.ppu = " ";
this.discount = " ";
this.np = new Double(0.0);;
}
}
public class New_Prog extends JFrame
implements TableModelListener
{
public JTextField total;
JLabel lbl_total;
int currentval;
public Vector data = new Vector();
public int current_row = 1;
public double total_net_price = 0.0;
private NumberFormat moneyFormat;
private NumberFormat percentFormat;
private DecimalFormat paymentFormat;
public New_Prog()
{
super("Invoice");
final DecimalFormat formatter = new DecimalFormat("###,##0.00" );
add_vector_data();
MyTableModel mymodel = new MyTableModel();
JTable line_items = new JTable( mymodel )
{
public void editingStopped(ChangeEvent e)
{
super.editingStopped(e);
reCalculate(getModel());
}
};
mymodel.addKeyListenerToTa bleCells(l ine_items) ;
mymodel.addTableModelListe ner(this);
line_items.setPreferredScr ollableVie wportSize( new Dimension(500, 70));
setUpFormats();
setUpDecimalEditor(line_it ems);
JScrollPane line_items_pane = new JScrollPane(line_items);
JPanel bottom = new JPanel();
bottom.setLayout(new BorderLayout());
JLabel lbl_total = new JLabel("Total :");
JTextField total = new JTextField(8);
bottom.add("West",lbl_tota l);
bottom.add("East",total);
JPanel pane = new JPanel();
pane.setBorder(BorderFacto ry.createE mptyBorder (20,20,20, 20));
pane.setLayout(new BorderLayout());
pane.add("Center",line_ite ms_pane);
pane.add("South",bottom);
setContentPane(pane);
total.setText("" + 0.0);
}
public void tableChanged(TableModelEve nt e)
{
//System.out.println("Hi") ;
//total.setText("" + 0.0);
}
private void setUpDecimalEditor(JTable table)
{
final DecimalField DecimalField = new DecimalField(5,3,moneyForm at);
DecimalField.setHorizontal Alignment( DecimalFie ld.RIGHT);
DefaultCellEditor DecimalEditor =
new DefaultCellEditor(DecimalF ield) {
//Override DefaultCellEditor's getCellEditorValue method
//to return an Integer, not a String:
public Object getCellEditorValue() {
return new Double(DecimalField.getVal ue());
}
};
table.setDefaultEditor(Dou ble.class, DecimalEditor);
}
void add_vector_data()
{
data.addElement(new rowrecord(current_row));
}
private void reCalculate(TableModel ml)
{
if (ml == null) return;
double total_np = 0.0;
if (current_row == 1) return;
for (int i=0;i<current_row;i++)
{
// System.out.println("Double " + ((Double)ml.getValueAt(i,6 )).doubleV alue());
total_np = total_np + ((Double)ml.getValueAt(i,6 )).doubleV alue();
}
System.out.println("Total " + total_np+ " " + current_row);
//total.setText("" + 0.0);
}
private void setUpFormats()
{
moneyFormat = NumberFormat.getNumberInst ance();
//XXXX: Workaround. With an empty positive suffix
//the format allows letters in the number.
((DecimalFormat)moneyForma t).setPosi tiveSuffix (" ");
percentFormat = NumberFormat.getNumberInst ance();
percentFormat.setMinimumFr actionDigi ts(3);
//XXXX: Workaround. With an empty positive suffix
//the format allows letters in the number.
((DecimalFormat)percentFor mat).setPo sitiveSuff ix(" ");
paymentFormat = (DecimalFormat)NumberForma t.getNumbe rInstance( );
paymentFormat.setMaximumFr actionDigi ts(2);
paymentFormat.setNegativeP refix("(") ;
paymentFormat.setNegativeS uffix(")") ;
}
class MyTableModel extends AbstractTableModel
{
final String columnNames[] = {"S.No","Site","Item","UM" ,"Price Per Unit",
"Discount","Net Price"};
final DecimalFormat formatter = new DecimalFormat("###,##0.00" );
public void addKeyListenerToTableCells (JTable tableV)
{
final JTable table = tableV;
java.awt.event.KeyAdapter listKeyListener = new java.awt.event.KeyAdapter( )
{
public void keyPressed(java.awt.event. KeyEvent e)
{
if ((e.getKeyChar()=='\n') && (table.getRowCount() == (table.getSelectedRow() + 1)) && (table.getColumnCount() == (table.getSelectedColumn() + 1)))
{
add();
table.clearSelection();
table.setColumnSelectionIn terval(1,1 );
table.clearSelection();
}
}
};
table.addKeyListener(listK eyListener );
}
public int getColumnCount()
{
return columnNames.length;
}
public int getRowCount()
{
return data.size();
}
public String getColumnName(int col)
{
return columnNames[col];
}
public Object getValueAt(int row, int col)
{
try {
rowrecord p = (rowrecord)(data.elementAt (row));
switch (col) {
case 0:
return new Integer(p.serial);
case 1:
return p.site;
case 2:
return p.item;
case 3:
return p.um;
case 4:
return p.ppu;
case 5:
return p.discount;
case 6:
return (Double)p.np;
}
} catch (Exception e) {
}
return "";
}
public boolean isCellEditable(int row, int col)
{
if (col > -1)
{
return true;
}
else
return false;
}
public void setValueAt(Object value, int row, int col)
{
double total_net_price = 0.0;
rowrecord u = (rowrecord)data.elementAt( row);
if (col == 1)
u.site = (String)value;
if (col == 2)
u.item = (String)value;
if (col == 3)
u.um = (String)value;
if (col == 4)
u.ppu = (String)value;
if (col == 5)
u.discount = (String)value;
if (col == 6)
{
// u.np = (Double)value.doubleValue( );
if (value instanceof Double)
{
u.np = (Double)value;
}
else
{
try
{
u.np = new Double(((Number)formatter. parse((Str ing)value) ).doubleVa lue());
}
catch (ParseException ex)
{
u.np = new Double(0.0);
}
}
}
data.setElementAt(u,row);
fireTableCellUpdated(row, col);
}
public void add()
{
//fireTableChanged(null);
int index0 = getRowCount();
int index1 = 0;
current_row++;
rowrecord p = new rowrecord(current_row);
data.addElement(p);
index1 = getRowCount();
fireTableRowsInserted(inde x0,index1) ;
}
}
public static void main(String arguments[])
{
try{
UIManager.setLookAndFeel(U IManager.g etCrossPla tformLookA ndFeelClas sName());
} catch (Exception e) {
System.err.println("Cant set look and Feel: " + e);
}
JFrame frame = new New_Prog();
WindowListener l = new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
};
frame.addWindowListener(l) ;
frame.pack();
frame.setVisible(true);
};
}
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.Abstract
import java.awt.*;
import java.util.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.text.*;
import javax.swing.DefaultCellEdi
class DecimalField extends JTextField {
private NumberFormat format;
public DecimalField(double value, int columns, NumberFormat f) {
super(columns);
format = f;
setValue(value);
}
public double getValue() {
double retVal = 0.0;
try {
retVal = format.parse(getText()).do
} catch (ParseException e) {
// This should never happen because insertString allows
// only properly formatted data to get in the field.
Toolkit.getDefaultToolkit(
System.err.println("getVal
}
return retVal;
}
public void setValue(double value) {
setText(format.format(valu
}
}
class rowrecord
{
int serial;
String site,item,um,ppu,discount;
Double np = new Double(0.0);
public rowrecord(int serial)
{
this.serial = serial;
this.site = " ";
this.item = " ";
this.um = " ";
this.ppu = " ";
this.discount = " ";
this.np = new Double(0.0);;
}
}
public class New_Prog extends JFrame
implements TableModelListener
{
public JTextField total;
JLabel lbl_total;
int currentval;
public Vector data = new Vector();
public int current_row = 1;
public double total_net_price = 0.0;
private NumberFormat moneyFormat;
private NumberFormat percentFormat;
private DecimalFormat paymentFormat;
public New_Prog()
{
super("Invoice");
final DecimalFormat formatter = new DecimalFormat("###,##0.00"
add_vector_data();
MyTableModel mymodel = new MyTableModel();
JTable line_items = new JTable( mymodel )
{
public void editingStopped(ChangeEvent
{
super.editingStopped(e);
reCalculate(getModel());
}
};
mymodel.addKeyListenerToTa
mymodel.addTableModelListe
line_items.setPreferredScr
setUpFormats();
setUpDecimalEditor(line_it
JScrollPane line_items_pane = new JScrollPane(line_items);
JPanel bottom = new JPanel();
bottom.setLayout(new BorderLayout());
JLabel lbl_total = new JLabel("Total :");
JTextField total = new JTextField(8);
bottom.add("West",lbl_tota
bottom.add("East",total);
JPanel pane = new JPanel();
pane.setBorder(BorderFacto
pane.setLayout(new BorderLayout());
pane.add("Center",line_ite
pane.add("South",bottom);
setContentPane(pane);
total.setText("" + 0.0);
}
public void tableChanged(TableModelEve
{
//System.out.println("Hi")
//total.setText("" + 0.0);
}
private void setUpDecimalEditor(JTable table)
{
final DecimalField DecimalField = new DecimalField(5,3,moneyForm
DecimalField.setHorizontal
DefaultCellEditor DecimalEditor =
new DefaultCellEditor(DecimalF
//Override DefaultCellEditor's getCellEditorValue method
//to return an Integer, not a String:
public Object getCellEditorValue() {
return new Double(DecimalField.getVal
}
};
table.setDefaultEditor(Dou
}
void add_vector_data()
{
data.addElement(new rowrecord(current_row));
}
private void reCalculate(TableModel ml)
{
if (ml == null) return;
double total_np = 0.0;
if (current_row == 1) return;
for (int i=0;i<current_row;i++)
{
// System.out.println("Double
total_np = total_np + ((Double)ml.getValueAt(i,6
}
System.out.println("Total " + total_np+ " " + current_row);
//total.setText("" + 0.0);
}
private void setUpFormats()
{
moneyFormat = NumberFormat.getNumberInst
//XXXX: Workaround. With an empty positive suffix
//the format allows letters in the number.
((DecimalFormat)moneyForma
percentFormat = NumberFormat.getNumberInst
percentFormat.setMinimumFr
//XXXX: Workaround. With an empty positive suffix
//the format allows letters in the number.
((DecimalFormat)percentFor
paymentFormat = (DecimalFormat)NumberForma
paymentFormat.setMaximumFr
paymentFormat.setNegativeP
paymentFormat.setNegativeS
}
class MyTableModel extends AbstractTableModel
{
final String columnNames[] = {"S.No","Site","Item","UM"
"Discount","Net Price"};
final DecimalFormat formatter = new DecimalFormat("###,##0.00"
public void addKeyListenerToTableCells
{
final JTable table = tableV;
java.awt.event.KeyAdapter listKeyListener = new java.awt.event.KeyAdapter(
{
public void keyPressed(java.awt.event.
{
if ((e.getKeyChar()=='\n') && (table.getRowCount() == (table.getSelectedRow() + 1)) && (table.getColumnCount() == (table.getSelectedColumn()
{
add();
table.clearSelection();
table.setColumnSelectionIn
table.clearSelection();
}
}
};
table.addKeyListener(listK
}
public int getColumnCount()
{
return columnNames.length;
}
public int getRowCount()
{
return data.size();
}
public String getColumnName(int col)
{
return columnNames[col];
}
public Object getValueAt(int row, int col)
{
try {
rowrecord p = (rowrecord)(data.elementAt
switch (col) {
case 0:
return new Integer(p.serial);
case 1:
return p.site;
case 2:
return p.item;
case 3:
return p.um;
case 4:
return p.ppu;
case 5:
return p.discount;
case 6:
return (Double)p.np;
}
} catch (Exception e) {
}
return "";
}
public boolean isCellEditable(int row, int col)
{
if (col > -1)
{
return true;
}
else
return false;
}
public void setValueAt(Object value, int row, int col)
{
double total_net_price = 0.0;
rowrecord u = (rowrecord)data.elementAt(
if (col == 1)
u.site = (String)value;
if (col == 2)
u.item = (String)value;
if (col == 3)
u.um = (String)value;
if (col == 4)
u.ppu = (String)value;
if (col == 5)
u.discount = (String)value;
if (col == 6)
{
// u.np = (Double)value.doubleValue(
if (value instanceof Double)
{
u.np = (Double)value;
}
else
{
try
{
u.np = new Double(((Number)formatter.
}
catch (ParseException ex)
{
u.np = new Double(0.0);
}
}
}
data.setElementAt(u,row);
fireTableCellUpdated(row, col);
}
public void add()
{
//fireTableChanged(null);
int index0 = getRowCount();
int index1 = 0;
current_row++;
rowrecord p = new rowrecord(current_row);
data.addElement(p);
index1 = getRowCount();
fireTableRowsInserted(inde
}
}
public static void main(String arguments[])
{
try{
UIManager.setLookAndFeel(U
} catch (Exception e) {
System.err.println("Cant set look and Feel: " + e);
}
JFrame frame = new New_Prog();
WindowListener l = new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
};
frame.addWindowListener(l)
frame.pack();
frame.setVisible(true);
};
}
ASKER
My mistake. I'd declared the total textfield twice. The problem is gone now. Thanks
ASKER
My mistake. I'd declared the total textfield twice. The problem is gone now. Thanks