Programatically change( edit?? ) JTable cell value

If my user changes the value in cell 'A', I'd like to change the value in cell 'B' to the results of a calculation performed using the new value in A with the present ( prior to changing ) value in B.
Example:
Cell: suggested_sell_price
Cell: cost_this_item
A change in the cost_this_item cell would be reflected in the suggested_sell_price,(upon hitting enter the values are stored in the DB)
Any suggestions would be greatly appreciated,

Thanks for the suggestions. I'm posting a test program of what I have at the moment, it has some of the behavior I'm looking for, but I can't seem to get the new value of an aedited cell and set the table model with the new value.
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class TE extends JFrame
     String[] cols = {"VAL_1", "VAL_2", "VAL_3"};
     Object[][] filler = {
                                   {new Double(100.00), new Double(100.00), new Double(100.00)},
                                   {new Double(200.00), new Double(200.00), new Double(200.00)},
                                   {new Double(400.00), new Double(400.00), new Double(400.00)}
     JTable table;
     TE(String title)
               super(title);
               this.setDefaultCloseOperation(EXIT_ON_CLOSE);
               MTM mtm = new MTM(3, cols.length);
               mtm.setColumnIdentifiers(cols);
               int nRows = filler.length;
               for(int i = 0; i < nRows; ++i)
                         mtm.setValueAt(filler[0], 0, i);
                         mtm.setValueAt(filler[1][i], 1, i);
                         mtm.setValueAt(filler[2][i], 2, i);
               table = new JTable(mtm);
               table.getColumnModel().getColumn(1).setCellEditor(new SimpleCellEditor());
               table.getColumnModel().getColumn(2).setCellEditor(new SimpleCellEditor());
               //table.getColumnModel().getColumn(2).setCellEditor(new SimpleCellEditor());
               JScrollPane jsp = new JScrollPane(table);
               Container c = getContentPane();
               c.add(jsp);
               setSize(300,300);
               setVisible(true);
     class MyMouseListener extends MouseAdapter
               public void mouseClicked(MouseEvent e)
                    if(e.getClickCount() == 2)
                              table.setValueAt("QQQQQQQ", 1,1);
class SimpleCellEditor extends AbstractCellEditor implements TableCellEditor, ActionListener
     JTextField tf = new JTextField();
     TableModel tm = table.getModel();
     protected EventListenerList listenerList = new EventListenerList();
     protected ChangeEvent changeEvent = new ChangeEvent(this);
     public SimpleCellEditor()
               super();                              
               tf.addMouseListener(new MyMouseListener());
               tf.addActionListener(this);
public void addCellEditorListener(CellEditorListener listener) {
listenerList.add(CellEditorListener.class, listener);
public void removeCellEditorListener(CellEditorListener listener) {
listenerList.remove(CellEditorListener.class, listener);
protected void fireEditingStopped()
          CellEditorListener listener;
          Object[] listeners = listenerList.getListenerList();
          for (int i = 0; i < listeners.length; i++)
               if (listeners[i] == CellEditorListener.class)
                         listener = (CellEditorListener) listeners[i + 1];
                         listener.editingStopped(changeEvent);
protected void fireEditingCanceled()
     CellEditorListener listener;
          Object[] listeners = listenerList.getListenerList();
               for (int i = 0; i < listeners.length; i++)
               if (listeners[i] == CellEditorListener.class)
                    listener = (CellEditorListener) listeners[i + 1];
                    listener.editingCanceled(changeEvent);
public void cancelCellEditing()
          fireEditingCanceled();
public boolean stopCellEditing()
          fireEditingStopped();
          return true;
public boolean isCellEditable(EventObject event)
          return true;
     public boolean shouldSelectCell(EventObject event)
     return true;
public Object getCellEditorValue()
     return tf.getText();
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
     if(tf.hasFocus() == true)
               tf.setBackground(Color.CYAN);
          return tf;
     public void actionPerformed(ActionEvent e)
          int row = table.getSelectedRow();
          int col = table.getSelectedColumn();
          double nVal = 0.00;
          Object currCostVal;
          Object currSellVal;
          Double costVal;
          Double sellVal;
          double newSellVal;
          double currentCost;
          if(table.getSelectedColumn() == 1)
               currCostVal = table.getValueAt(row, col+1);
               currSellVal = table.getValueAt(row, col);
               costVal = new Double(currCostVal.toString());
               currentCost = costVal.doubleValue();
               sellVal = new Double(currSellVal.toString());
               newSellVal = sellVal.doubleValue();
               nVal = newSellVal*currentCost*100/100;
               System.out.println("Recommended sell-price after change: " + nVal);
          }else if(table.getSelectedColumn() == 2 )
                    currCostVal = table.getValueAt(row, col);
                    currSellVal = table.getValueAt(row, col-1);
                    costVal = new Double(currCostVal.toString());
                    currentCost = costVal.doubleValue();
                    sellVal = new Double(currSellVal.toString());
                    newSellVal = sellVal.doubleValue();
                    nVal = newSellVal*currentCost*100/100;
                    System.out.println("Recommended sell-price after change: " + nVal);
                    System.out.println("Cost column selected " + nVal);
}// end simple cell editor
class MTM extends DefaultTableModel
          MTM(int rows, int cols)
                    super(rows, cols);
public static void main(String args[])
          TE te = new TE("Test of table cell update");

Similar Messages

  • How to programatically select different JTable cells

    Dear all,
    I need to programatically select different JTable cells.
    I have to make the inverse selection. So if the user has a table of one column and 10 rows, and selects rows 3,6,8, the inverse selection should select all the other remainig cells and deselect 3,6, and 8.
    I tried using the following but it does not work ?
    for (int i = 0; i < table.getRowCount(); i++) {
    table.changeSelection(i, 0, true, false);
    Hope someone can help.
    Regards,
    Kanita

    Dear all,
    I need to programatically select different JTable cells.
    I have to make the inverse selection. So if the user has a table of one column and 10 rows, and selects rows 3,6,8, the inverse selection should select all the other remainig cells and deselect 3,6, and 8.
    I tried using the following but it does not work ?
    for (int i = 0; i < table.getRowCount(); i++) {
    table.changeSelection(i, 0, true, false);
    Hope someone can help.
    Regards,
    Kanita

  • JTable cell value doesn't change with user input

    I'm making a program that uses a custom table model (extends AbstractTableModel). The problem is when I type a value in one of the table cells, then press enter (or click outside the cell), the value goes back to what it was originally. So for example, a cell has "oldvalue", I type in "newvalue", press enter, and now the cell still reads "oldvalue". I figured the renderer would automatically update the cell by calling MyTableModel.setValueAt (...), but maybe I need a listener to do this? let me know. thanks

    alright, well basically I'm making a database manager
    and thought it would be easier to extend
    AbstractTableModel and then do all the queries inside
    the methods instead of listening for events. Second
    thing, I put a debug statement and setValueAt never
    gets called when you type in a new cell value. How
    does it update the cell then is my question?It's your TableModel bug but a much better advice would be that you should use
    DefaultTableModel instead of extending AbstractTableModel. The DefaultTableModel
    is usually more than enough for an ordinary JTable application.
    The simplest and standard way of handling DB data from JTable is updating
    vectors for DefaultTableModel data with your new DB data set. You don't need
    to worry about low-level event firing, cell editor control etc. if you use
    DefaultTableModel. See API documentation of DefaultTableModel closely.

  • Dynamically Rendering and editing JTable cell

    Hi all,
    I wonder if some body can help me.
    As in my application each cell in Jtable returns java Object. and what i am trying to do is based on each object returned in cell my renderer is going to change dynamically. for example if the object returned is primitive data types the renderer is defualt, if the returned object is Map, Set or List, then the Cell Renderer should show clickable button with icon on right hand side and TextField on left hand side and so on for other objects. i am able get renderer for Map, set or list, which is button on right hand side of cell and text field on left hand side displaying toString of Object. then what i want is when i click button it should show those values in popup window and if i double click it should edit the cell which i am able to do it. so how can i handle events or what i have to do to make button clickable. if any body come accross these situations or got idea. please let me know how to move further.
    Thanks,
    Kotesh.

    Hi,
    Thanks for your advise and as i said i am able to get render for Map as (TextField in left hand side+Button with icon in right hand side side) of Cell. but what i need is when i click button which is on right hand, then i should be able to show popup wvindow with map values and if i double click on TextField which is on right hand side, then i should be able to edit Cell which is happening. but i am not able to get popup window when i click button on right hand side of cell. basically i am not sure how to handle events on cell and the button on right hand side?
    if some one can guide me that will be great as i am in big trouble.
    Thanks
    Kotesh.

  • Data changes in JTable cell.

    Hi all,
    On editing a cell in a Jtable ,necessary changes must get enforced in the corresponding cells of the same JTable.For example,I have fields called Quantity ,SalePrice and TotalAmount in a Jtable,where the Quantity field is editable.When i edit the Quantity value,a calculation (Changed Quantity *SalePrice)=TotalPrice must happen .Hence the Total Amount field must get Updated now.This must occur when I edit the Quantity and press Tab.No Button action is involved.Please tell me how to do this.the JTable does not use any TableModel.Thanks in advance.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    As I said in your other post, your table does have a model.
    What you seem to be saying is that your table has some calculated columns. If so then you should create an explicit table model so that when a cell is update the setValueAt() method performs any calculations based on this change and updates the rest of the model.
    Remember to fire the appropriate events after the change.

  • Start or stop edit jtable cell editing

    Hello,
    I got a problem with the jtable DefaultModel isCellEditable.
    If I set the IsCellEditable to false, I would not be able to enable the cell selection as and when I want it.
    What I have in mind is the add a mouselister so that if the user select a row using fast left mouse click like the procedure shown below
    private class MouseClickHandler extends MouseAdapter {
    public void mouseClicked(MouseEvent event) {
    int no_mouseclick = 0;
    no_mouseclick = event.getClickCount();
    if (no_mouseclick >= 2) {
    int cur_row = 0;
    cur_row = table.getSelectedRow();
    // table.setColumnSelectionAllowed(true);
    // table.setRowSelectionAllowed(true);
    for (int i=0;i<table.getColumnCount();i++){
    table.editCellAt(cur_row,i);
    System.out.println("mouse row--->" + cur_row);
    I could overwrite the IsCellEditable to true to enable that particular or cell contains in that row to be able to accept input and overwrite any data which in my case obtained from the Sql database a sort of like input module using tabulation . I am also thinking of using text component or combobox to display the value for user selection , but I do not know how to enable a particular cell for editing if the Jtable created is using a non-editable DefaultModel. If I set the IsCellEditable to true, every single cell would be enable for editing , and this defeat the purpose of enable user input only upon double mouseclicks.
    By the way , I am interested to know how to track the data changes in the cell within the jtable so that only those have been modified are notify from the Table model and updated into the Sql table
    Could anyone of you out there provide some hints please
    Thanks

    Hello,
    Tablemodellistener could detect the changes in the data, how about the backend database updating and transactional activity that must be associated with the data changes?
    What is on my mind is that , the moment there is changes in the data detected by the TableModellistener, whatever records associated with or brougt up by Jtable would be all deleted from the database and then follow by the new set of new records to be inserted into the database. The disadvantage of this method is that everytime the backend database connection and activity need to be executed the moment there is a change in the data in the jtable cell. For example the user may be just amendment to only one cell , but all the records associated need to be deleted and then inserted again.
    Perhaps there are better solution to deal with Jtable and JDBC backend connection where in this case, I am using JDO to undertake the database activity like the observable modelling .
    Could someone provide the hint please
    Thank

  • Way to listen for change in JTable cell?

    I am having troubles trying to catch a key event while the user is entering text inside a given JTable cell (x/y location). The JTable only seems to manage String objects in it's cells so I can't place a JTextField in there with a KeyListener on it.
    Currently, I can only get control of the application once the user has left the cell they are editing.
    Does anyone have an example of a JTable 'cell KeyListener' scenario? At this point I want to see if I can print 'hello world' each time I type a character within a cell. Then I'll go from there....

    If you want to know when the contents of a cell have been updated you should use a TableModelListener.
    If you want to know when a character is added/removed from the cell editor then you need to first understand how this works with a simple text field.
    Typically you would use a DocumentListener to receive notifies of a change to the text field. However, within the DocumentEvent you wouldn't be able to change the text field as this notification comes after the text field has already been updated.
    If you need to ability to intercept changes to the text field before they happen, then you would need to use a DocumentFilter. An example of using a DocumentFilter is given in the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#filter]Text Component Features.
    Once you get your regular text field working the way you want, the next step to create a DefaultCellEditor using this JTextField and use this editor in your JTable. The above tutorial also has a section on using editors in a table.

  • JTable Cell Value needs to hided

    Hi,
    I have 5 columns in a JTable. The first column is a checkbox. The second column is non editable. The third, fourth and fifth columns are editable. Whan I click a check box, I am performing a database operation and based on the output, I am setting values to for the column 3, 4 and 5.
    My requirement: I need to perform the database operation only for the first time of the check box click. If I uncheck the checkbox, the values in column 3, 4 and 5 needs to be disappeared. If I check the check box again, I need the values to be visible. Basically, I will do database calls only for the first time. From second time onwards, I need to just hide the text in the particular cells (if the checkbox is unchecked) and make the cell values visible (if the checkbox is checked) In JTable API, there are no methods to hide a cell value or I am unable to figure it out. Please help me.
    Regards
    subbu

    Alirght here is some code. This is a bit messy but I guess the solution is clear. It make use of a combination of renderers, ie the Sun's DefaultTableCellRenderer (for the first column to get the checkboxes) and a custom renderer for the rest of the columns.
    Also, a MouseListener is added so that on clicking the first column, a repaint is forced to ensure the values in the cells disappear.
    * @(#)CheckableRow.java
    * @author icewalker2g
    * @version 1.00 2007/12/27
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.util.*;
    import java.io.*;
    public class CheckableRow extends JFrame {
        public JTable table;
        public DefaultTableModel model;
        public CheckableRow() {
            super("Checkable Row");
            createUI();
        public void createUI() {
            Vector<String> cols = new Vector<String>();
                cols.addElement("Col 1");
                cols.addElement("Col 2");
                cols.addElement("Col 3");
                cols.addElement("Col 4");
                cols.addElement("Col 5");
            Vector<Object> rows = new Vector<Object>();
            model = new DefaultTableModel(rows, cols);
            for(int i = 0; i < 5; i++) {
                Vector<Object> row = new Vector<Object>();
                    row.addElement( false );
                    row.addElement("Data");
                    row.addElement("Col 3 Data " + (i+1));
                    row.addElement("Col 4 Data " + (i+1));
                    row.addElement("Col 5 Data " + (i+1));
                model.addRow( row );
            table = new JTable(model) {
                CellValueRenderer renderer = new CellValueRenderer();
                public TableCellRenderer getCellRenderer(int row, int col) {
                    if(col > 1) {
                        return renderer;   
                    return super.getCellRenderer(row, col);
                public Class getColumnClass(int col) {
                    if( col == 0) {
                        return Boolean.class;
                    return super.getColumnClass(col);
                public boolean isCellEditable(int row, int col) {
                    if( col != 1 ){
                        return true;
                    return false;
            table.addMouseListener( new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    if( table.columnAtPoint( e.getPoint() ) == 0 ) {
                        table.repaint();
            getContentPane().add( new JScrollPane(table), BorderLayout.CENTER );
            pack();
            setLocationRelativeTo(null);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setVisible(true);
        public class CellValueRenderer extends DefaultTableCellRenderer {
            public CellValueRenderer() {
                super();
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int col) {
                DefaultTableCellRenderer renderer = (DefaultTableCellRenderer)
                super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
                if( table.getValueAt(row, 0).toString().equals("true") && col > 1) {
                    renderer.setText("");
                } else {
                    renderer.setText( value == null ? "" : value.toString() );
                return renderer;
        public static void main(String[] args) {
            new CheckableRow();
    }ICE

  • Edit JTable Cell

    Hi,ALL
    I have create normal JTable.and set all cell Editable.
    When I double clike a cell, I can modify the value on the cell.
    However, When I use getValueAt(row, col)
    it still give me the orginal value, not the modified value!
    Do I lost something? Or do I need to implement something else?
    any idea would be greated appreciated

    It may also depend on when you're calling getValueAt. If you're doing it before the edit has committed to the table model (ie, before setValueAt has been called) then the underlying data won't yet have been updated.
    It would be useful if you could supply some example code for what you're trying to do (post it in [ code ] tags please!).
    Hope this helps.

  • How can we give the option to edit the cell value of a table to user

    i have a Jtable which shows the entered values of all the expenses daily.Before saving them i want to provide an option to user for editing.How this is possible.
    I went through the TableCellEditor interface .I think it needs to be implemented some code there.
    help me out in implementing those methods.

    Might I suggest reading the JTable tutorial? And/Or perhaps purchasing a book on swing?

  • Non-editable JTable cells?

    Is there any way to make all the cells in a JTable non-editable? In the API I see the isEditable method, but no setEditable method. Any suggestions?

    You have to set it in the TableModel.
    TableModel model = new AbstractTableModel()
    public int getRowCount()
    return 10;
    public int getColumnCount()
    return 5;
    public Object getValueAt(int row, int column)
    return "( "+row+","+column+" )";
    public boolean isCellEditable(int row,int column)
    return false;
    The one given above is a sample to show you how to set a cell non-editable on the cell. You have to customize it for your table model.
    Thanks,
    Kalyan

  • JTable cell value

    I have a custom cell renderer for JTable, and this cell renderer is also a listener for some event. The cell renderer receives new value as events, since it is a listener. The cell renderer must upadte this value as a table cell. Simple call this.setText does not work, as it must somehow call the "getTableCellRendererComponent" method of the TableCellRenderer interface that it implements. How can the cell renderer force the table to update itself, as the cell renderer has received his new value. What will be a good approach here?
    TIA,
    - Manish

    Manish -
    Would you be able to post your idea?
    I have a column in a table that I added
    a check box to so that the user can select
    or deselect the data. Sometimes when
    the check box is selected or deselected it
    doesn't register until I click another field.
    Would your idea work to correct this?
    Thanks!

  • Dynamically resize JTable cell to fit a JList

    Hi!
    I've been banging my head trying to add some dynamic behavior to a TableCellEditor. In short I'm trying trying to make it resize the height of the current row (the one it is in) to reflect the changes made to the JList used to let the user edit the cells value (which is a list of items).
    I've come across some threads dealing with the problem of resizing a cell to fit its content. This however is usually only done once (in the 'getTableCellEditorComponent' function) and so only provides half the answer. Also, since the editor is only active during cell editing I've been trying to make it revert to the old cell height after the editing is done.
    So far I have not come up with any decent solution to this problem and was hoping someone out there might have an idea or have read something similar and can point me to something helpful... anyone?
    Cheers!
    Teo

    The Swing tutorial on[url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html]How to Use Tables shows how to dynamically change the size to Table Columns.
    If you need help calculating the acutal size then try searching the forum. Using keywords "resize jtable column" (keywords I took directly from your topic title) I found some promising postings.

  • How to edit jtable programmatically?

    id like to know how to edit jtable cell programmatically.
    thanks!

    override
    getTableCellEditorComponent in customized
    TableCellEditor.Hi,
    hmm ... if that's that, what he want to know? - I guess, he wants to know how to change values of the JTable by program.
    Every JTable has an underlying TableDataModel that holds the values of the tablecells. You can retrieve this model by the getModel()-method of the JTable.
    To get a value from the model use method getValueAt(row,column) of the model.
    To set a value in the model use method setValueAt(object,row,column) of the model.
    See the TableModel-interface-Documentation for other methods.
    greetings Marsian

  • Default cell values for column not properly saved in uir file in labwindows 2009 (9.1.0 427)?

    I've run into a strange problem with the table control.  Basically, even though I set default cell values for a particular column as numeric, when I try to add items to the list it tries to add them as strings, and returns an error message that it is expecting *char instead of int.  Furthermore, when I open the uir file that contains the table in question in 2010, it appears as if the default cell values for that column are still set as strings, even though in 2009 when I open the uir file it shows as numbers.  I tried converting the uir to C code, and sure enough the C code indicated that the column still is a string type.
    I've gone ahead and made a small project to show the issue.  If you open this project in labwindows 2009 and click on the table in the table_bug.uir, and edit default cell values for column 1, you will see that the cell settings have type as numeric and data type as int.  When you run the project, however, it will fail with an error message saying that it is looking for a *char.  When this same project is loaded into labwindows 2010, clicking on the table in table_bug.uir and edit default cell values (column 1) shows the type as string.  When I change this to numeric (and change numeric attribute to int), this runs fine in 2010.  I tried simply changing the uir in 2010, and then using it in 2009, but 2009 complains that the uir is from a newer version (understandable).  If there is any workaround that would let me continue to use 2009 for the time that would be great.
    Any help would be greatly appreciated.
    thanks,
    Alex Corwin
    Solved!
    Go to Solution.
    Attachments:
    table_bug.zip ‏324 KB

    I opened the UIR in 2009 (but I have 2009 SP1) and it still showed that the default value for the first column was a string. I didn't have any problems changing it to a numeric int, and then building and running the project without error.
    Here are a few things you can try:
    1) Change the default value to a string. OK out of the dialog, re-enter the dialog, and change it back to Numeric int. Resave and see if the problem has gone away.
    2) You said you get a ".UIR is from a newer version" error when opening the 2010 UIR in 2009. Does the UIR still open if you click okay? Often times this will work just fine. Assuming you don't have any problems with this, make a minor change to the UIR in 2009, such as moving the table to the left, and then back to the right and then re-save. See if your program works now.
    Kevin B.
    National Instruments

Maybe you are looking for

  • MacBook Pro to S Video

    Hello, need some help. I am trying to connect my Macbook Pro to a projector with only an s-video and composite video connector (Sony VPL W400Q). I know I need a MiniDisplayport to VGA adapter (I think) and then possibly a VGA-to-S Video converter, or

  • What is the best way to write 10 channels of data each sampled at 4kHz to file?

    Hi everyone, I have developed a vi with about 8 AI channels and 2 AO channels... The vi uses a number of parallel while loops to acquire, process, and display continous data.. All data are read at 400 points per loop interation and all synchronously

  • How can I delete files from Dreamweaver?

    I spent the day creating HTML files for a class assignment. I thought I had all the files in a folder, but they were not. I have since lost the files but not the folders. All I have left are the labels from the files. I need to delete the files and s

  • Issue with Drag&Drop between table and tree component

    I want to drag table rows and drop it on the tree node. I use following code to achieve this: <af:table value="#{bindings.pricingObjects.collectionModel}" var="row" rows="#{bindings.pricingObjects.rangeSize}" emptyText="#{bindings.pricingObjects.view

  • Cisco ISE: Non-complaint Timer for Users

    Dear Folks, What is the time for the non-complaint user state? How long a user stays in non-complaint state? and how to change the time? Kindly respond fast. Thanks, Regards, Mubasher