JTable edits wrong cell on mouseclick

I am using an editable JComboBox as my cell editor. When the user is editing a cell and clicks on another cell with the mouse, the value of the cell they were editing is inserted into the cell that they clicked on. Can anyone please help me. Thanks.

The Swing tutorial has a working example:
http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#combobox

Similar Messages

  • JTable cannot make cell non-editable

    I have create a JTable using the DefaultTablemodel. I want to make the cells non editable. I have overwritten the method isCellEditable with that shown below but when I double click any cell it still let me edit the cell. Someone please show me what is wrong.
    public boolean isCellEditable(int cellrow, int cellcol)
    return(false);
    // if (cellcol == 0)
    // return(false);
    // else
    // return(true);
    Regards
    pslloo

    Look at the tutorial! This sample works.
    Hope this help.
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.awt.event.*;
    public class TableDemo extends JFrame {
        private boolean DEBUG = true;
        public TableDemo() {
            super("TableDemo");
            MyTableModel myModel = new MyTableModel();
            JTable table = new JTable(myModel);
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this window.
            getContentPane().add(scrollPane, BorderLayout.CENTER);
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
        class MyTableModel extends AbstractTableModel {
            final String[] columnNames = {"First Name",
                                          "Last Name",
                                          "Sport",
                                          "# of Years",
                                          "Vegetarian",
                                          "essai"};
            final Object[][] data = {
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false), new Integer(3)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true), new Integer(3)},
                {"Kathy", "Walrath",
                 "Chasing toddlers", new Integer(2), new Boolean(false), new Integer(3)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true), new Integer(3)},
                {"Angela", "Lih",
                 "Teaching high school", new Integer(4), new Boolean(false), new Integer(3)}
            public int getColumnCount() {
                return columnNames.length;
            public int getRowCount() {
                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.
                if (col < 2) {
                    return false;
                } else {
                    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) {
                if (DEBUG) {
                    System.out.println("Setting value at " + row + "," + col
                                       + " to " + value
                                       + " (an instance of "
                                       + value.getClass() + ")");
                if (data[0][col] instanceof Integer                       
                        && !(value instanceof Integer)) {                 
                    //With JFC/Swing 1.1 and JDK 1.2, we need to create   
                    //an Integer from the value; otherwise, the column    
                    //switches to contain Strings.  Starting with v 1.3,  
                    //the table automatically converts value to an Integer,
                    //so you only need the code in the 'else' part of this
                    //'if' block.                                         
                    //XXX: See TableEditDemo.java for a better solution!!!
                    try {
                        data[row][col] = new Integer(value.toString());
                        fireTableCellUpdated(row, col);
                    } catch (NumberFormatException e) {
                        JOptionPane.showMessageDialog(TableDemo.this,
                            "The \"" + getColumnName(col)
                            + "\" column accepts only integer values.");
                } else {
                    data[row][col] = value;
                    fireTableCellUpdated(row, col);
                if (DEBUG) {
                    System.out.println("New value of data:");
                    printDebugData();
            private void printDebugData() {
                int numRows = getRowCount();
                int numCols = getColumnCount();
                for (int i=0; i < numRows; i++) {
                    System.out.print("    row " + i + ":");
                    for (int j=0; j < numCols; j++) {
                        System.out.print("  " + data[i][j]);
                    System.out.println();
                System.out.println("--------------------------");
        public static void main(String[] args) {
            TableDemo frame = new TableDemo();
            frame.pack();
            frame.setVisible(true);
    [\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Default behaviour of the Escape key while editing a cell in JTable??

    Hi all,
    i have a Jtable which get its data from an own model object which extends DefaultTableModel.
    If i overwrite the isCellEditable(row, col) method within the tablemodel object and set a specific column to editable, then i notice while editing a cell in that column that the default behaviour of the Escape key is that independet from what you have entered before in to the cell the editing stops and the cell gets the value it had before editing.
    This is the case for me even if i apply a custom editor to a column (one that extends DefaultCellEditor). It is just a JTextField that limits the number of digits a user can enter. Everything works fine. If the user edits the cell and presses ENTER or the "down arrow key" i can check what he has entered with the help of the getCellEditorValue() method. But if the user hits the ESC key after editing a cell this method is not invoked!!!
    My question is :
    is there any way to detect that the user cancels editing with the ESC-key.
    this is very important for me because if the user goes editing the cell i lock the related record in the database, if i cannot detect this it is locked till the application terminates.
    Thanks for any help in advance

    I try override the JTable editingCanceled() ==> does not work.
    I try the addCellEditorListener( CellEditorListener l ) ==> does not work.
    Finally, I try the addKeyListener ==> it works.
    Here is a quick demo. program:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class Test {
    public static void main(String[] args){
    JFrame f = new JFrame();
    String[] colName = {"a", "b"};
    String[][] rowData = {{"1", "2"}, {"3", "4"}};
    JTable table = new JTable(rowData, colName);
    JTextField t = new JTextField(10);
    t.setBackground(Color.red);
    t.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
    // do what ever you want ex. un-lock table
    System.out.println("ESCAPE");
    DefaultCellEditor editor = new DefaultCellEditor(t);
    TableColumnModel colModel = table.getColumnModel();
    for (int i = colModel.getColumnCount()-1; i >= 0; i--) {
    colModel.getColumn(i).setCellEditor(editor);
    f.setContentPane(new JScrollPane(table));
    f.pack();
    f.setVisible(true);

  • Help with editing a cell in a JTable. DESPERATE

    Hi! Is there someone out there that could help with some source code for editing a cell in my JTable when I run it as an applet??
    It works fine when I run it as an application.
    I manage to select the row and write a number in it, but I can't get out of the cell (it seems that the program stops??). I want to enter an integer in a cell and when I click enter or with the mouse in an other cell the value that I enter should update some other cell( multiply the entered value with some fixed number and update a cell in a second coloumn)
    I am really desperate now..... I have thought about using a MouseListener....
    I am using a tablemodel that is from AbstractTableModel.

    Are you using some cell editors?
    While converting inside them, you might be getting some exceptions (like parseexception)which is stopping you from proceeding further.
    Are you using your own tablemodel with custom datatypes?
    Hope this helps,
    Ramkumar

  • JTable and last cell edited

    Hi all,
    I have a jtable that is populated from an sql table.
    When I edit the cells, I push on a botton that updates the table.
    The problem I am facing is in the last cell edited, I need to click on another cell for me to be able to read its new value. i.e. in another word the cell needs to loose focus for me to be able to read is new values.
    Thanks in advance for your help.
    Best regards.
    Saadi MONLA

    Seems like a bug in JTable. Best solution is probably when the routine that feeds the new values into the JTable is completed, force a focus on a different cell and then back to your cell using an API method. If an API method doesn't exist to force focus to another cell (I just looked and didn't see one) then maybe executing a repaint() or something like that will cause it to redraw correctly.

  • Programmatically Editing a Cell Not Working

    Hi Guys,
    I'm trying to automatically begin editing a cell within a JTable as soon as the table is displayed.
    I've tried using the table.editCellAt(int row, int col) method but it just seems to have no effect.
    I've set the cell editable within my custom table class (and I know it is because if I double click on the cell or type anything then the editor is displayed).
    FYI I'm using Java 1.5
    Anyone got any ideas?

    Does nobody know how to automatically engage the editor component of a JTable programatically i.e. without having to click on the cell?? The code I gave you above works fine for me in JDK1.4.2. Why don't you post the 10 line demo program you are using to test my suggestion. That way people can determine whether you test code is wrong or 1.5 isn't working.

  • Edit table cells

    i have edited the setValueAt method of the TableModel interface to enable editing of cells in my JTable - in-situ. This works fine. However, i would like it so that when any change is made to the table data, it is automatically sorted depending on how it was sorted before the change was made. i have:
    public void setValueAt(Object aValue, int row, int col) {
            if (col == 0) {
                bookList[row].setBookNumber(Integer.parseInt((String)aValue)); // Populates cell with new book number
                if (lastSort == "number") {
                    listByNumber();
            } else {
                if (col == 1) {
                    bookList[row].setTitle((String)aValue); // Populates cell with new book title
                } else {
                    if (col == 2) {
                        bookList[row].setAuthorPrename((String)aValue); // Populates cell with new author prename
                    } else {
                        bookList[row].setAuthorSurname((String)aValue); // Populates cell with new author surname
        }i would put more if statements in later for different sort methods but at the moment ill just stick with one. My problem is that the array is being sorted correctly, but the table doesn't update automatically to show the change. what DOES happen - is when you click on each row of the table, it changes until it is in the correct order. this leads me to think that the sorting works fine, but somehow my table model isnt reflecting the changes? can any help me update the table in real time?

    no luck :( i tried:
       public void setValueAt(Object aValue, int row, int col) {
            if (col == 0) {
                bookList[row].setBookNumber(Integer.parseInt((String)aValue)); // Populates cell with new book number  
                listByNumber();
                fireTableDataChanged();and extended AstractTableModel but it still didnt work. is there anything else i would need to do?

  • Preventing JTree updates from uncompleted JTable edits

    Hello there!!
    I have an applet that displays an xml file in a JTree. Each node of the table represents specific elements of the xml file (some are not displayed by design). Also on the applet is a JTable that updates the displayed information depending on what node of the tree is clicked. The information displayed in the table includes names and values of attributes and names and values of xml elements not displayed in the JTree.
    I can edit values in the table and update that tree effectively, so that is not a problem.
    The problem I have is that if the user enters a value in the table, does not press enter and then clicks on another tree node, the entered value is copied into the new tree node. I would like to ignore all values if the user does not specifically press enter.
    I have seen some code examples in previous posts that partially work, but can't get the entered values to be totally ignored.
    I'm currently using the following code to handle the 'didn't press enter' bug.
            table.getEditorComponent().addFocusListener(
                    new java.awt.event.FocusListener(){
                public void focusGained(java.awt.event.FocusEvent e) {}
                public void focusLost(java.awt.event.FocusEvent e){
                    if ( table.getEditingRow() > -1 &&
                            table.getEditingColumn() > -1 ){
                        ((javax.swing.DefaultCellEditor)table.getCellEditor()).stopCellEditing();
            });So my question is: How do I prevent the value entered in the table cell from being copied to the newly clicked on tree node? Any assistance would be great.
    Thanks (even just for reading!)
    Simon
    PS. When are we going to see the back of the stupid censorship in this forum?

    Not too sure if this will help but here goes...
    Normally in a JTable, editing is automatically stopped when the enter key is pressed so there is no need to do anything special there. If you don't want editing to stop when the mouse is clicked elsewhere in the table, what you should do is call cancelEditing() instead of stopEditing() in your focusLost method.
    ;o)
    V.V.

  • HTMLB TableView Iterator & Edit columns, cells

    Hi friends,
    I am getting errors when , I tried to edit the columns, & Cells of  HTMLB TableView by using Iterator.Actually, I got the whole edit buttons and when I edit the values of particular column & cell fileds, it is not saving the values, instead it is giving same old values. The code I used is as follows.
    <u><b>To Edit the  columns,</b></u>
    method
    IF_HTMLB_TABLEVIEW_ITERATOR~GET_COLUMN_DEFINITIONS.
    FIELD-SYMBOLS: <def> LIKE LINE OF p_column_definitions.
      APPEND INITIAL LINE TO p_column_definitions ASSIGNING <def>.
    <def>-COLUMNNAME = 'STUDENTID'.<def>-EDIT = 'X'.
    endmethod.
    <u><b>To Edit the  cells,</b></u>
    RENDER_CELL_START Method:
    method
    IF_HTMLB_TABLEVIEW_ITERATOR~RENDER_CELL_START.
    CASE p_column_key.
    WHEN 'ICON'.
    WHEN 'STUDENTID'.
           IF p_edit_mode IS NOT INITIAL.
    ENDIF.
    WHEN 'SDATE'.
           IF p_edit_mode IS NOT INITIAL.
    ENDIF.
    ENDCASE.
    endmethod.
    <u><b>To Edit the SDATE cells,</b></u>
    WHEN 'SDATE'.
      IF p_edit_mode IS NOT INITIAL.
    DATA: date TYPE STRING.
    date = m_row_ref->SDATE.
    p_replacement_bee = CL_HTMLB_INPUTFIELD=>FACTORY(
                          id        = p_cell_id
                           value     = date
                           type      = 'DATE'
                             showHelp  = 'TRUE'
                             cellValue = 'TRUE' ).
                               ENDIF.
    Why the either column or cell is not saving the new values, when I edit them? where it went wrong? please mail me in this regard.
    regards
    CSM Reddy

    Hi REDDY CSM 
    To learn coding these Methods.
    You need to learn everything from scratch about MVC.
    To learn functionalities of Methods in Controller and how to use them,its Better,if you start with some tutorial(Little application) on MVC.
    Here is link,Just follow this,You will get some Exposure to these methods.
    http://help.sap.com/saphelp_erp2005/helpdata/en/c8/101c3a1cf1c54be10000000a114084/frameset.htm
    Rest keep posting whenever you face and Problem..
    Happy Coding..!!
    Vijay Raheja

  • Wrong cell #

    I have been without my cell for over a month now.  My son was helping to activate my new phone and it has the wrong cell #.  It is showing (removed) and it should be (removed).  I NEED to activate my cell, so how does it get changed to the correct #? 
    Private info removed as required by the Terms of Service.
    Message was edited by: Admin Moderator

    Hello txflwr48! I regret the difficulties you've been having while activating your new phone. I'd love to help, but I recommend that we take our conversation to direct message instead of here in the public forum. If you have not yet gotten your device activated, please follow these steps to follow my handle (DionM_VZW) send me a direct message: http://vz.to/1gBiqkv
    DionM_VZW
    Follow us on Twitter www.twitter.com/vzwsupport

  • Edit two cells at the same time

    Hi friends!
    Is it possible to edit two cells of JTable at the same time?
    When I click on a cell, the cell enters in edit mode, but I want to edit another cell at the same time. To do that I use this method :
    GrelhaHorarios.editCellAt(row,col);The problem is the other cell returns to the rendered form and only one is in edit mode. Regard that I don't to want introduce values manually, but with the setValueAt(...) method.
    Thanks in advance.

    You can only edit a single cell at a time.
    You do not need to place a cell in edit mode to use the setValueAt(...) method.

  • Mirror JTable Edits

    I have a JTable on one internal frame for data entry. I have a duplicate jTable on a different internal frame. Is there an easy way to mirror the tables as the user edits the cells?

    Sure it does. You didn't implement the suggestion correctly.
    Create a simple JFrame with two tables and edit either table and the other will be updated automatically.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    Don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the posted code retains its original formatting.

  • Make my JTable editable

    in mu Jtable when i click a cell and change the value inside, the JTable does NOT save the value, (when i come back to the Jtable i find the OLD value and not the new one),
    Please help me to make my JTable editable, so when i change the value in any cell this value is saved when i leave this cell...
    Thanks to any help

    >
    in my Jtable when i click a cell and change the value inside, the JTable does NOT save the value, Kindly show your code here...
    When i come back to the Jtable i find the OLD value and not the new one)you came back from where ? are you starting the application again or just switching between forms?
    Please help me to make my JTable editable, so when i change the value in any cell this value is saved when i leave this cell...Do u want to save values permanently ? and please share your code and let use know what exactly you wanna do.

  • How to set jtable editable?

    how to set jtable editable?

    Hi,
    Doubleclick on a particular cell to get the cellEditor for editing.
    Cheers :)
    Nagaraj

  • Editing in cell

    i just switched from pc/excel to mac/Numbers, and i can't figure out how to (a) change my preferences so that the cursor doesn't move down a cell after i press return and (b) edit in cell. in excel and lotus, you pressed f2 to edit in cell (and to switch between editing in cell and moving the cursor around the sheet); in Numbers i can't find that option.

    Hi dre1973,
    Welcome to Numbers forum.
    1. Regarding the cursor movement: Enter or Return moves it down Tab moves it to the right. As in other programs there isn't any way to make a change.
    2. In cell editing: double click on the cell.
    If those answers are not satisfactory please contact Numbers development team: At the top of the screen to the right of the blue apple click Numbers > Provide Numbers Feedback. Your request goes directly to the Numbers team. Then hope your request is implemented in the next version of Numbers.
    Because of different design philosophies MS and Apple do things differently, neither is incorrect.
    Sincerely,
    RicD

Maybe you are looking for