Update JTable cells via setValueAt

Hello all,
I'm trying to implement a setValueAt method using an arrayList.....no success.What listeners should I have set up(For JTable or my table model)? I am new at this and I'm trying to update the JTable cells after a query from some db. Could anyone help?
When trying to change the a value in the table I get these errors:
"Exception occurred during event dispatching:
java.lang.ClassCastException: java.lang.String
at CachingResultSetTableModel.getValueAt(CachingResultSetTableModel.java:37)
at javax.swing.JTable.getValueAt(JTable.java:1711)
at javax.swing.JTable.prepareRenderer(JTable.java:3530)"
public void setValueAt(Object avalue, int r, int c){
if(r < cache.size()){
row[c] = (Object[])cache.set(r, avalue);
fireTableCellUpdated(r, c);
}//setValueAt
*********For reference here's the getValueAt method*************************
public Object getValueAt(int r, int c){
if(r < cache.size()){
row = (Object[])cache.get(r);
return row[c];
else
return null;
}//getValueAt

I would think that everone who starts off with JTable will have a couple of concept problems. I am also going thru this learnig curve. It looks to me ( the blind leading the blind etc) like your basic table has strange data in it. The problem is occuring when the JTable is trying to setup the data from the table model.
I don't think its anything to do with setValueAt.
I kept going back to TableMap, TableSorter and JDBCAdaptor examples and copying the code from them to come right.> I debug by putting a System.out .... in all the methods until I get to where the code is giving trouble.
Good luck [email protected]
Hello all,
>
I'm trying to implement a setValueAt method using an
arrayList.....no success.What listeners should I have
set up(For JTable or my table model)? I am new at
this and I'm trying to update the JTable cells after a
query from some db. Could anyone help?
When trying to change the a value in the table I get
these errors:
"Exception occurred during event dispatching:
java.lang.ClassCastException: java.lang.String
at
CachingResultSetTableModel.getValueAt(CachingResultSetT
bIleModel.java:37)
at javax.swing.JTable.getValueAt(JTable.java:1711)
at
javax.swing.JTable.prepareRenderer(JTable.java:3530)"
public void setValueAt(Object avalue, int r, int c){
if(r < cache.size()){
row[c] = (Object[])cache.set(r, avalue);
fireTableCellUpdated(r, c);
}//setValueAt
*********For reference here's the getValueAt
method*************************
public Object getValueAt(int r, int c){
if(r < cache.size()){
row = (Object[])cache.get(r);
return row[c];
else
return null;
}//getValueAt

Similar Messages

  • Update jtable cell via numeric keypad

    Hi,
    I have a problem, trying to figure out how to input numbers in a jtextfield in a jtable cell, from a group of jbuttons (rendered as a numeric keypad). I can get the cell to focus, but when I click on one of the jbuttons in the keypad, the cell loses focus and nothing is printed. I can update the cell by directly typing from the keyboard; that works fine. But I'm lost when trying to do it from the touch-screen keypad. Can anyone point me in the right direction. I assume I need to attach additional listeners somewhere.
    Thanks in-advance.
    Lee

    I can get the cell to focus, Then the code for you button would need to be something like:
    String text = (String)table.getValueAt(...);
    String updated = text + button.getText();
    table.setValueAt(updated, ...);

  • Update JTable - Cell

    i tried out the sample http://java.sun.com/docs/books/tutorial/uiswing/components/example-swing/TableDemo.java. if i enter a new value and klick into another cell of the table all works fine. if i click on the table header after editing the cell the old value appears in the cell. if i enter signs directly after the click on the table header the text appended to the old value of the edited cell.
    i hope, anybody can help me.

    Hmm, the suggestion given above appears to work when focus is gained on all other components, so the table header must have to logic to "cancel" cell editing. You can add your own MouseListener to "save" the edited data to the table header:
    table.getTableHeader().addMouseListener( new MouseAdapter()
         public void mousePressed(MouseEvent e)
              JTableHeader header = (JTableHeader)e.getSource();
              JTable table = header.getTable();
              if (table.isEditing())
                   table.getCellEditor().stopCellEditing();
    });

  • Indeterminate JProgressBar inside JTable cell

    I am able to put a JProgressBar inside a JTable cell, via a custom renderer to do so, however, I am unable to make the progress bar show the indeterminate animation. Any ideas? I calledbar.setIndeterminate( true ); and it doesn't seem to want to show. Is the JTable preventing it?
    (should I include more of my code?)

    Your JProgressBar is used to render the table cell only when that cell of the JTable needs to be rendered and the JProgressBar has no say in this.
    I don't know why you would want to do this but to do this I would set up timer that fired a tree model event to say that the content of the cell had changed. This would trigger the cell to be re-painted. I think, but I can't be sure, that you will not be able to use
    bar.setIndeterminate( true );
    You may have to craft your own progress bar to make this easy.

  • How to write an element in a  JTable Cell

    Probably it's a stupid question but I have this problem:
    I have a the necessity to build a JTable in which, when I edit a cell and I push a keyboard button, a new Frame opens to edit the content of the cell.
    But the problem is how to write something in the JTable cell, before setting its model. Because, I know, setCellAT() method of JTree inserts the value in the model and not in the table view. And repainting doesn't function!
    What to do??
    Thanks

    Hi there
    Depending on your table model you should normally change the "cell value" of the tablemodel.
    This could look like:
    JTable table = new JTable();
    TableModel model = table.getModel();
    int rowIndex = 0, columnIndex = 0;
    model.setValueAt("This is a test", rowIndex, columnIndex);
    The tablemodel should then fire an event to the view (i.e. JTable) and the table should be updated.
    Hope this helps you

  • Problem in event handling of combo box in JTable cell

    Hi,
    I have a combo box as an editor for a column cells in JTable. I have a event listener for this combo box. When ever I click on the JTable cell whose editor is combo box,
    I get the following exception,
    Exception occurred during event dispatching:
    java.lang.NullPointerException
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.setDispatchComponent(Unknown Source)
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.mousePressed(Unknown Source)
         at java.awt.AWTEventMulticaster.mousePressed(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Can any one tell me how to over come this problem.
    Thanks,
    Raghu

    Here's an example of the model I used in my JTable. I've placed 2 comboBoxes with no problems.
    Hope this helps.
    public class FileModel5 extends AbstractTableModel
    public boolean isEditable = false;
    protected static int NUM_COLUMNS = 3;
    // initialize number of rows to start out with ...
    protected static int START_NUM_ROWS = 0;
    protected int nextEmptyRow = 0;
    protected int numRows = 0;
    static final public String file = "File";
    static final public String mailName = "Mail Id";
    static final public String postName = "Post Office Id";
    static final public String columnNames[] = {"File", "Mail Id", "Post Office Id"};
    // List of data
    protected Vector data = null;
    public FileModel5()
    data = new Vector();
    public boolean isCellEditable(int rowIndex, int columnIndex)
    // The 2nd & 3rd column or Value field is editable
    if(isEditable)
    if(columnIndex > 0)
    return true;
    return false;
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c)
    return getValueAt(0, c).getClass();
    * Retrieves number of columns
    public synchronized int getColumnCount()
    return NUM_COLUMNS;
    * Get a column name
    public String getColumnName(int col)
    return columnNames[col];
    * Retrieves number of records
    public synchronized int getRowCount()
    if (numRows < START_NUM_ROWS)
    return START_NUM_ROWS;
    else
    return numRows;
    * Returns cell information of a record at location row,column
    public synchronized Object getValueAt(int row, int column)
    try
    FileRecord5 p = (FileRecord5)data.elementAt(row);
    switch (column)
    case 0:
    return (String)p.file;
    case 1:
    return (String)p.mailName;
    case 2:
    return (String)p.postName;
    catch (Exception e)
    return "";
    public void setValueAt(Object aValue, int row, int column)
    FileRecord5 arow = (FileRecord5)data.elementAt(row);
    arow.setElementAt((String)aValue, column);
    fireTableCellUpdated(row, column);
    * Returns information of an entire record at location row
    public synchronized FileRecord5 getRecordAt(int row) throws Exception
    try
    return (FileRecord5)data.elementAt(row);
    catch (Exception e)
    throw new Exception("Record not found");
    * Used to add or update a record
    * @param tableRecord
    public synchronized void updateRecord(FileRecord5 tableRecord)
    String file = tableRecord.file;
    FileRecord5 p = null;
    int index = -1;
    boolean found = false;
    boolean addedRow = false;
    int i = 0;
    while (!found && (i < nextEmptyRow))
    p = (FileRecord5)data.elementAt(i);
    if (p.file.equals(file))
    found = true;
    index = i;
    } else
    i++;
    if (found)
    { //update
    data.setElementAt(tableRecord, index);
    else
    if (numRows <= nextEmptyRow)
    //add a row
    numRows++;
    addedRow = true;
    index = nextEmptyRow;
    data.addElement(tableRecord);
    //Notify listeners that the data changed.
    if (addedRow)
    nextEmptyRow++;
    fireTableRowsInserted(index, index);
    else
    fireTableRowsUpdated(index, index);
    * Used to delete a record
    public synchronized void deleteRecord(String file)
    FileRecord5 p = null;
    int index = -1;
    boolean found = false;
    int i = 0;
    while (!found && (i < nextEmptyRow))
    p = (FileRecord5)data.elementAt(i);
    if (p.file.equals(file))
    found = true;
    index = i;
    } else
    i++;
    if (found)
    data.removeElementAt(i);
    nextEmptyRow--;
    numRows--;
    fireTableRowsDeleted(START_NUM_ROWS, numRows);
    * Clears all records
    public synchronized void clear()
    int oldNumRows = numRows;
    numRows = START_NUM_ROWS;
    data.removeAllElements();
    nextEmptyRow = 0;
    if (oldNumRows > START_NUM_ROWS)
    fireTableRowsDeleted(START_NUM_ROWS, oldNumRows - 1);
    fireTableRowsUpdated(0, START_NUM_ROWS - 1);
    * Loads the values into the combo box within the table for mail id
    public void setUpMailColumn(JTable mapTable, ArrayList mailList)
    TableColumn col = mapTable.getColumnModel().getColumn(1);
    javax.swing.JComboBox comboMail = new javax.swing.JComboBox();
    int s = mailList.size();
    for(int i=0; i<s; i++)
    comboMail.addItem(mailList.get(i));
    col.setCellEditor(new DefaultCellEditor(comboMail));
    //Set up tool tips.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for mail Id list");
    col.setCellRenderer(renderer);
    //Set up tool tip for the mailName column header.
    TableCellRenderer headerRenderer = col.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the Mail Id to see a list of choices");
    * Loads the values into the combo box within the table for post office id
    public void setUpPostColumn(JTable mapTable, ArrayList postList)
    TableColumn col = mapTable.getColumnModel().getColumn(2);
    javax.swing.JComboBox combo = new javax.swing.JComboBox();
    int s = postList.size();
    for(int i=0; i<s; i++)
    combo.addItem(postList.get(i));
    col.setCellEditor(new DefaultCellEditor(combo));
    //Set up tool tips.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for post office Id list");
    col.setCellRenderer(renderer);
    //Set up tool tip for the mailName column header.
    TableCellRenderer headerRenderer = col.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the Post Office Id to see a list of choices");
    }

  • How to update JTable when clicking outside the table?

    Hi
    (Sorry if this has been asked before but I can't seem to see exactly how to do this from previous posts.)
    I have a JTable which sits on a jPanel which itself is part of a frame.
    When I click anywhere outside the table when I'm editing a cell in the table, how do I end the edit mode of the table (so that the cell is updated with the new contents).Currently I can only update a cell's contents during edit when hitting 'enter' or by clicking on another cell within the table.
    It seems that the following code is used in the process but I'm sure that I'm still missing something:
    if(table1.getCellEditor()!=null)
    table1.getCellEditor().stopCellEditing();
    If anyone out there knows how to do this,I'd really appreciate hearing how.
    Thanks a lot
    LGS

    Thanks for your comments but I'm still having problems.
    When I add the following code:
    table1.addFocusListener(new java.awt.event.FocusAdapter()
    public void focusLost(java.awt.event.FocusEvent evt)
    if (table1.getCellEditor() != null)
    table1.getCellEditor().stopCellEditing();
    and then try to edit my table,as soon as I double click on any cell in the table,my setValueAt method in my Table Model is being called before I even edit the cells contents. The above code is in the same method in which I actaully create table1 i.e.createTable().
    Can anyone help?

  • 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.

  • Can not show the JCheckBox in JTable cell

    I want to place a JCheckBox in one JTable cell, i do as below:
    i want the column "d" be a check box which indicates "true" or "false".
    String[] columnNames = {"a","b","c","d"};
    Object[][] rowData = {{"", "", "", Boolean.FALSE}};
    tableModel = new DefaultTableModel(rowData, columnNames);
    dataTable = new JTable(tableModel);
    dataTable.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(new JCheckBox()));
    But when i run it, the "d" column show the string "false" or "true", not the check box i wanted.
    I do not understand it, can you help me?
    Thank you very much!
    coral9527

    Do not use DefaultTableModel, create your own table model and you should implement the method
    getColumnClass to display the boolean as checkbox ...
    I hope the following colde snippet helps you :
    class MyModel extends AbstractTableModel {
              private String[] columnNames = {"c1",
    "c2"};
    public Object[][] data ={{Boolean.valueOf(true),"c1d1"}};
         public int getColumnCount() {
         //System.out.println("Calling getColumnCount");
         return columnNames.length;
    public int getRowCount() {
    //System.out.println("Calling row count");
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    data[row][col] = value;
    fireTableCellUpdated(row, col);

  • Update Jtable from access database

    as the title suggests help me guys... till now i have a database and some contents in it.. when the application starts the table is filled with contents of the database.. now whenever i add or remove a row in the databse i want to show it in the table... i have a Vector called dbData with the present contents of the database.. i want to update jtable with contents of dbData.... how to do it??

    the best things i can see to do is
    JTable table = new Jtable(.....); // this was ur table before;
    deleteRow(table); // you deleted the row
    // now you have a vector containing all the data for the rows;
    // but you need a vector containing the columns for the rows too
    //so now you do
    table = new JTable(dbData,columnnames);
    repaint();dbData must be a vector of vectors;
    dbData.elementAt(1) return a vector with all the data for row one
    so dbData.elementAt(1).elementAt(1) will be the data for row 1 column 1
    // dbData will be the data still remaining in the table
    or instead of the above you could use a nested for loop and set each element one at a time
    Object temp;
    int numberofRows = dbData.elementCount();
    int numberofColumns = db.elementAt(0).elementCount();
    for(int row = 0; row < numberofColumns;row++)
    for( int column = 0; column < numberofRows; column++)
      temp = dbData.elementAt(row).elementAt(column);
      table.setValueAt(temp,row,column);
    }

  • 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.

  • Updating JTable Contents

    I'm having trouble refreshing a JTable after changing it's 2D Object array data. Perhaps this is a stupid question, but any advice would be appreciated.
    Basically I've been building from the SimpleTableDemo.java file in the "How to Use Tables" tutorial. I set Object[][] data to a 2D Object array that is modified by other parts of my program.
    I added the public void tableChanged(TableModelEvent e) function to detect data changes, displaying a simple System.out, but it never seems to get called.
    Is there any way that the JTable can observe changes in the Object[][] data array and update it's self accordingly? I'm never sure if rows are being added or removed.
    I hope that made sense, and thank-you in advance to anyone who replies.
    -Arthur

    Couple of things...
    Whenever you change the contents of your TableModel you need to fire the appropriate event to get the JTable to update the viewed rows... in your case it sounds like you would have to call the "fireTableDataChanged()" method defined by AbstractTableModel so that your contents will be viewed.
    Also... it is rare that you really need to update the entire contents of your table model, most the time it is more efficient to just update the cell or row your need and call the appropriate "fire..." method to update
    Hope this helps
    Josh Castagno
    http://www.jdc-software.com

  • How to manipulate jtable cell?

    Hi experts,
    I created a jtable with a BC4J related to the jtable.
    I do not know how to update a cell and how to insert a new row in the jtable.
    Would someone please tell me where I can find the document about manipulating a jtable?

    Have a look at the source code of JUNavigationBar. In that class, look for JUActionBinding(_buttons[BUTTON_FIRST]   , bind, JUActionBinding.ACTION_FIRST, false);As you can see you will need the JUActionBinding class.

  • Making some JTable cells nonfocusable

    I have a JTable in which the TAB keys moves focus from cell to cell. Fine, but how can certain columns (or individual cells) be disabled from recieving focus ?? For "normal" JComponent-derived objects on a panel then I could call component.setFocusable(false); on the components I do not want to receive focus. What is the equivalent for a JTable cell given that it isn't a normal component: it is rendered via a TableRenderer ?

    I suppose you are using JDK 1.4 beacuse I am using it now. :-)
    I override the method:   protected boolean accept(Component aComponent) {
      } which is in the class LayoutFocusTraversalPolicy.

  • Updating 6085 firmware via a Mac

    Apparently impossible as Nokia (are you listening ?)persist in turning a blind eye/deaf ear toward Mac users pleas for a Mac Suite. Feasibility of using iSync already noted though I'll need a plug in for my new 6085 - from www.media.de (whence directed on an Apple Discussion Forum t'other day)
    So I assume none of us Nokia/Mac folk can ever update our Cell/Mobile phone firmware. I'll be eligble (thanks to my Vodafone contract) for a new phone in 18 months time... and if Nokia still leave me out in the cold I'll desert them.

    I, too, hope that Nokia puts out a firmware updater for the Mac.
    On the astronomy side of things, Meade Telescopes is known for its Windows software, but kindly provides for an Internet based Java application for updating. Perhaps there's a way for Nokia to do that... but it would be best handled via a dedicated Mac application.
    It makes sense for them to develop such given the explosion in Mac users. Nokia phones make a lot of sense for those of us Mac users who find the iPhone wonderful but too steep!

Maybe you are looking for