FocusLost event for JTable during cell editing

When a cell in a JTable is getting edited, how can I get notified of the focusLost event? I added the focus listener using JTable.addFocusListener, but the focusLost of the listener is not called when a cell inside the table is getting edited (it works fine otherwise). I am aware of the client property terminateEditOnFocusLost to solve this problem in 1.4 but I can't use it since I am still on 1.3.1_04.
Suggestions welcome.

http://forum.java.sun.com/thread.jsp?forum=57&thread=431440

Similar Messages

  • Need help serializing an AbstractTableModel for a JTable with cell editing.

    Fun times are ahead. Here we go!
    I have a JTable that contains data I'd like to serialize out to a file to be restored and viewed later.
    So I tried saving the AbstractTableModel subclass out to a file. Whenever I do this, I get the following error message:
    java.io.NotSerializableException: javax.swing.JTable$CellEditorRemover
    Now I know for fact that serializing an AbstractTableModel that was installed in a JTable without cell editing works just fine (my old code did exactly that). As a result, I think that the code that handles events in the AbstractTableModel contains references back out to the JTable, which causes the JTable to be saved no matter what (even though I'm just interested in saving the TableModel only). It causes a bigger file than normal, but file size is not an issue. The only issue I have is that CellEditorRemover (an undocumented inner class of JTable), which is automatically installed for JTables with editable cells, is not serializable.
    This leads to the following questions:
    1. Is there a way to avoid serialization/deserialization of the CellEditorRemover inner class of JTable?
    2. Is there a way to save an AbstractTableModel without saving all of the event listeners associated with it?
    I think an answer to either of these questions would go a long way towards solving my problem. Otherwise, I'll resign myself to weeping silently in the corner of my office.
    Thanks!

    I would suggest that if you can you only save the
    data... but i would do this by using the
    externalizable interface.
    What you will need to do is have the
    writeExternal(ObjectOutputStream out) and
    readExternal(ObjectOutputStream out) methods in your
    class. These will be responsiable for saving the
    data.
    Here's an example of what you can do in these
    methods... this is just a little tidbit from a program
    i've written.public void writeExternal(ObjectOutput out) throws
    IOException {
              out.writeInt(size);
              out.writeObject(drawName);
              out.writeInt(playersLength);
    for(int i = 0; i < playersLength; i++)
    ) out.writeObject(players);
              out.writeInt(seedsLength);
    for(int i = 0; i < seedsLength; i++)
    ) out.writeObject(seeds[i]);
              out.writeInt(drawLength);
    for(int i = 0; i < drawLength; i++)
    ) out.writeObject(draw[i]);
    public void readExternal(ObjectInput in) throws
    IOException, ClassNotFoundException {
              size = in.readInt();
              drawName = (String)in.readObject();
              playersLength = in.readInt();
    for(int i = 0; i < playersLength; i++) players[i] =
    = (String)in.readObject();
              seedsLength = in.readInt();
    for(int i = 0; i < seedsLength; i++) seeds[i] =
    = (String)in.readObject();
              drawLength = in.readInt();
    for(int i = 0; i < drawLength; i++) draw[i] =
    = (String)in.readObject();
    You can now use your class as you would a Serializable
    class, but it will only save the data
    Hope this helped
    webaf409java
    I forgot to add some critical information in my original post. My apologies. :(
    I've thought about using Externalizable, but am hesitant to use it because the application would no longer be able to read in files using the old save format (ie, AbstractTableModels for JTables without CellEditorRemovers ).  I want to preserve the ability to read the old saved AbstractTableModel formats if possible. 
    Do you know of a way to revert to the default deserialization mechanism from readExternal?  This way, during deserialization, I could do a quick test on the object being read and have the ability to default to the regular deserialization mechanism if the object is of the old type or continue with the new Externalizable stuff if the object is one of the new type.  Maintaining file compatibility is key.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • JTable - disable cell editing for whole table

    I need to know how to disable cell editing for the whole of a JTable. Is there an easy way of doing this??

    you can do it very easy :)
    just override AbstractTableModel's isCellEditable(int row, int col) function
    and return false is ok.
    Hope this helps!

  • FocusLost event for JTextField sometimes triggered, sometimes not

    Some background.
    A column in a table consists of a number of cells.
    Each cell can be a JTextField or a JComboBox.
    I have written a CellEditor who returns either a JTextField or a JComboBox depending on some conditions.
    The JTextField listens for a FocusLost event to update the database.
    When I leave the first cell the FocusLost event is always triggered.
    For the ther cells the FocusLost event is triggeed every now and then.
    In the mean time I have found a simple workaround by placing the update code in method getCellEditorValue() which is called always by the table when moving to the next cell.
    I am just curious if someone has an explanation for this inconsistent behaviour of the FocusLost event.
    Code is below:
    * QuoteProductPropertyValueEditor.java
    * Created on May 4, 2005
    package tsquote.gui;
    * @author johnz
    import java.awt.Component;
    import java.util.EventObject;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import tsquote.controller.QueryHandler;
    import tsquote.exception.FinderException;
    import tsquote.gui.control.GenericTableModel;
    import tsquote.gui.control.Table;
    import tsquote.util.Messager;
    public class QuoteProductPropertyValueEditor implements TableCellEditor {
          * We use EvetListenerList, because it is thread-safe
         protected EventListenerList listenerList = new EventListenerList();
         protected ChangeEvent changeEvent = new ChangeEvent(this);
         private List<Component> componentList = new ArrayList();
         private Map<Integer, Integer> indexMap = new HashMap(); // maps row to index
         private Table table;
         private int currentRow;
         private QueryHandler queryHandler = QueryHandler.getInstance();
         public QuoteProductPropertyValueEditor() {
              super();
         public Object getCellEditorValue() {
              Component component = componentList.get(indexMap.get(currentRow));
              if (component instanceof JComboBox) {
                   JComboBox comboBox = (JComboBox) component;
                   return comboBox.getSelectedItem();
              JTextField textField = (JTextField) component;
              return textField.getText();
         public Component getTableCellEditorComponent(
                   JTable jTable,
                   Object value,
                   boolean isSelected,
                   int row,
                   int column) {
              final int thisRow = row;
              System.out.println("getTableCellEditorComponent(): thisRow=" + thisRow);
              table = (Table) jTable;
              currentRow = thisRow;
              if (!indexMap.containsKey(thisRow)) {
                   System.out.println("Control added: thisRow=" + thisRow);
                   indexMap.put(thisRow, componentList.size());
                   // This is actually a tsquote.gui.control.Table
                   GenericTableModel genericTableModel = table.getGenericTableModel();
                   List<Map> list = genericTableModel.getList();
                   Map recordMap = list.get(thisRow);
                   Boolean hasList = (Boolean) recordMap.get("product_property.has_list");
                   if (hasList) {
                        JComboBox comboBox = new JComboBox();
                        componentList.add(comboBox);
                        comboBox.addActionListener(new ActionListener() {
                             public void actionPerformed(ActionEvent event) {
                                  fireEditingStopped();
                        for (int i=0; i<=row +1; i++) {
                             comboBox.addItem("Item" + i);
                   } else {
                        JTextField textField = new JTextField();
                        componentList.add(textField);
                        textField.addFocusListener(new FocusAdapter() {
                             public void focusLost(FocusEvent e) {
                                  System.out.println("textField: thisRow=" + thisRow);
                                  JTextField textField = (JTextField) componentList.get(indexMap.get(thisRow));
                                  String newValue = textField.getText();
                                  fireEditingStopped();
                                  updateQuoteProductProperty(thisRow, newValue);
                        String text = (String) recordMap.get("quote_product_property.value");
                        textField.setText(text);
              Component component = componentList.get(indexMap.get(thisRow));
              if (component instanceof JComboBox) {
                   JComboBox comboBox = (JComboBox) component;
                   if (value == null) {
                        comboBox.setSelectedIndex(0);
                   } else {
                        comboBox.setSelectedItem(value);
              } else {
                   JTextField textField = (JTextField) component;
                   textField.setText((String) value);
              return component;
         private void updateQuoteProductProperty(
                   int row,
                   String newValue) {
              // Get PK quote_prodcut_property from list
              GenericTableModel genericTableModel = table.getGenericTableModel();
              List<Map> list = genericTableModel.getList();
              Map modelRecordMap = list.get(row);
              String storedValue = (String) modelRecordMap.get("quote_product_property.value");
              // If nothing changed, ready
    //          if (storedValue == null) {
    //               if (newValue == null) {
    //                    return;
    //          } else {
    //               if (storedValue.equals(newValue)){
    //                    return;
              // Update model
              modelRecordMap.put ("quote_product_property.value", newValue);
              Integer quoteProductPropertyID = (Integer) modelRecordMap.get("quote_product_property.quote_product_property_id");
              try {
                   queryHandler.setTable("quote_product_property");
                   queryHandler.setWhere("quote_product_property_id=?", quoteProductPropertyID);
                   Map recordMap = queryHandler.getMap();
                   recordMap.put("value", newValue);
                   recordMap.get("quote_product_property.value");
                   queryHandler.updateRecord("quote_product_property", "quote_product_property_id", recordMap);
              } catch (FinderException fE) {
                   Messager.warning("Cannot find record in quote_product_property\n" + fE.getMessage());
         public void addCellEditorListener(CellEditorListener listener) {
              listenerList.add(CellEditorListener.class, listener);
         public void removeCellEditorListener(CellEditorListener listener) {
              listenerList.remove(CellEditorListener.class, listener);
         public void cancelCellEditing() {
              fireEditingCanceled();
         public boolean stopCellEditing() {
              fireEditingStopped();
              return true;
         public boolean isCellEditable(EventObject event) {
              return true;
         public boolean shouldSelectCell(EventObject event) {
              return true;
         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);
    }

    The JTextField listens for a FocusLost event to update the database.I don't recommend using a FocusListener. Wouldn't you get a FocusLost event even if the user cancels any changes made to the cell?
    Whenver I want to know if data has changed in the table I use a TableModelListener:
    http://forum.java.sun.com/thread.jspa?threadID=527578&messageID=2533071
    I'm not very good at writing cell editors so I don't. I just override the getCellEditor method to return an appropriate editor. Here's a simple example:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableComboBoxByRow extends JFrame
         ArrayList editors = new ArrayList(3);
         public TableComboBoxByRow()
              // Create the editors to be used for each row
              String[] items1 = { "Red", "Blue", "Green" };
              JComboBox comboBox1 = new JComboBox( items1 );
              DefaultCellEditor dce1 = new DefaultCellEditor( comboBox1 );
              editors.add( dce1 );
              String[] items2 = { "Circle", "Square", "Triangle" };
              JComboBox comboBox2 = new JComboBox( items2 );
              DefaultCellEditor dce2 = new DefaultCellEditor( comboBox2 );
              editors.add( dce2 );
              String[] items3 = { "Apple", "Orange", "Banana" };
              JComboBox comboBox3 = new JComboBox( items3 );
              DefaultCellEditor dce3 = new DefaultCellEditor( comboBox3 );
              editors.add( dce3 );
              //  Create the table with default data
              Object[][] data =
                   {"Color", "Red"},
                   {"Shape", "Square"},
                   {"Fruit", "Banana"},
                   {"Plain", "Text"}
              String[] columnNames = {"Type","Value"};
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              JTable table = new JTable(model)
                   //  Determine editor to be used by row
                   public TableCellEditor getCellEditor(int row, int column)
                        int modelColumn = convertColumnIndexToModel( column );
                        if (modelColumn == 1 && row < 3)
                             return (TableCellEditor)editors.get(row);
                        else
                             return super.getCellEditor(row, column);
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              TableComboBoxByRow frame = new TableComboBoxByRow();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }

  • Recognize ENTER hit on JTable after cell edit is done

    Hello,
    I'm trying to find a way to detect a key press (specifically, Enter key) after editing a value on a JTable. That is, when I double click on a cell in my table, edit the value and press enter after the editing is done, I want to be able to detect pressing the enter. Adding a normal keyListener to the JTable object won't do it. So I'm trying to find a new way. Please help me out!
    Here's my SSCCE:
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class MyTable extends JTable {
         JTable table;
         public MyTable(Object[][] data, Object[] columnNames)
              JFrame frame = new JFrame("My Table");
              table = new JTable(data, columnNames);
              JScrollPane scrollPane = new JScrollPane(table);
              frame.getContentPane().add(scrollPane);
              frame.setSize(100, 100);
              frame.setVisible(true);
              table.addKeyListener(new KeyAdapter()
                   public void keyPressed(KeyEvent e)
                        if(e.getKeyChar()==KeyEvent.VK_ENTER)
                             System.out.println("Key Pressed");
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              Object [][]data = {{"item1"},{"item2"},{"item3"},{"item4"},{"item5"}};
              String []columnNames = {"ITEMS"};
              MyTable table = new MyTable(data, columnNames);
    }Message was edited by:
    programmer_girl

    First of all you don't use a KeyListener to check for KeyEvents on a compponent. You use "Key Bindings" and Actions:
    http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html
    When you are "editing" a cell then focus is on the edtitor used by cell editor. For a cell containing Strings a JTextField is used. Since a JTextField supports an ActionListener all you need to do is get the JTextField and add an ActionListener to the text field. You can use the getDefaultEditor(...) method of JTable and cast the editor to a DefaultCellEditor. From there you can then get the editing component.
    Of course the question is why are you specifically worried about the enter key? What if the user tabs to the next cell or uses the mouse to click on a different cell. There is more than one way to finish editing a cell.

  • Double click event for JTable.....

    All,
    I would like to display some data on double_click a selected row from the JTable. How do I code the double_click event in the following program. Please advise.
    Here is the code:
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Vector;
    class TableTest extends JFrame {
    MyTableModel myModel;
    JTable table;
    JButton button;
    JButton buttonQuery;
    int count = 0;
    public TableTest() {
    myModel = new MyTableModel();
    table = new JTable(myModel);
    table.setPreferredScrollableViewportSize(new Dimension(500, 200));
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    getContentPane().add(button = new JButton("Add Row"),
    BorderLayout.SOUTH);
    getContentPane().add(buttonQuery = new JButton("Query"), BorderLayout.NORTH);
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    Object [] aRow = new Object [8];
    for (int i=0; i<5; i++) {
    aRow = new Integer(count+i);
    myModel.addRow(aRow);
    count += 10;
    buttonQuery.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    System.out.println(myModel.getRowCount());
    System.out.println(myModel.getValueAt(1, 3));
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    class MyTableModel extends AbstractTableModel {
    protected final String[] headers =
    { "No", "Vehicle No", "Date of Loss", "Image Type", "Image Description", "Claim Type", "Scan Date", "User Id" };
    Vector data;
    MyTableModel() {
    data = new Vector();
    public int getColumnCount() {
    return headers.length;
    public int getRowCount() {
    return data.size();
    public Object getValueAt(int row, int col) {
    if (row < data.size() && col < 8) {
    Object [] aRow = (Object []) data.elementAt(row);
    return aRow[col];
    } else {
    return null;
    public void addRow(Object [] aRow) {
    data.addElement(aRow);
    fireTableRowsInserted(data.size()-1, data.size()-1);
    public static void main(String[] args) {
    TableTest frame = new TableTest();
    frame.pack();
    frame.setVisible(true);
    }

    Thanks, but I get 1 error:
    'Cannot resolve symbol' -class MouseInputAdapter
        import java.awt.event.MouseAdapter;
    Also say if I need to get 'column data' from selected
    row, what will be the command like ?
        int col = table.columnAtPoint(p);>
    Best Regards

  • Event for JTable column move

    Can someone tell me which event is fired when a column is moved (dragging from one location to the next) in a JTable. I need to know when the move ends.
    Thanks

    RTM javax.swing.event.TableColumnModelEvent

  • How to raise on click event for Single Markable cell in WD Table

    Hi All,
        I want to raise an event when a cell is clicked on Single Markable Cell and get the row and column of that cell.
    I have tried all the events of the table and also On Enter event of input Field.
    But I am not able to trigger on click event .
    Please help me out. Points will be rewarded.
    Thanks,
    Anil

    Hi Anil,
            If the cell editor is a link to action then it triggers the ON CLICK event , Write the following code into
           the ON CLICK event handler to get the selected Row and Column ID.
          Event Properties is a node with two attributes Name and Value of type string.
    data: lr_node type ref to if_wd_context_node,
    lt_event_properties type wd_this->elements_event_properties,
    ls_event_properties type wd_this->element_event_properties.
    field-symbols: <l_value> type any.
    * fill internal table
    ls_event_properties-name = 'COLUMN_ID'.
    ls_event_properties-value = r_param->column.
    append ls_event_properties to lt_event_properties.
    ls_event_properties-name = 'INDEX'.
    ls_event_properties-value = r_param->index.
    append ls_event_properties to lt_event_properties.
    ls_event_properties-name = 'ATTRIBUTE'.
    ls_event_properties-value = r_param->attribute.
    append ls_event_properties to lt_event_properties.
    assign r_param->value->* to <l_value>.
    ls_event_properties-name = 'VALUE'.
    ls_event_properties-value = <l_value>.
    append ls_event_properties to lt_event_properties.

  • Making a Table cell editable. Please Help

    Hello there,
    I have written an Inner class called CallHeaderRenderer
    which is used to select to highlight a row from a table.
    But i am unable to edit the column data I click on.
    Please can any one tell me how to edit the column value when you double click on it??
    Attached is my Inner class used to select the concerned row.
    I am unable to edit the concerned column.....
    Please help.!!!
    What is the statement to make the cell editable!!!
    class CallHeaderRenderer extends DefaultTableCellRenderer{
    public CallHeaderRenderer(){
    super();
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column){
    // Set the highlight for record chosen.
    super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    return this;
    }

    A renderer has nothing to do with editing the cell. I suggest you read this section from the Swing tutorial on "Using Tables" for an explanation of how tables work. The tutorial will give one method for making a cell editable:
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
    Here is an alternate way to make a cell editable:
    table = new JTable( ... )
        public boolean isCellEditable(int row, int column)
            //  All columns, except the first, are editable
            if (column == 0)
                return false;
            else
                return true;
    };

  • Custom UIView not receiving touch events for fast mouse clicks in simulator

    I'm having a problem in the simulator where if I click fast in a UIView inside a table cell that is setup to receive touch events, it doesn't receive them. But if I click slow (holding down the button for a little bit) the view gets the touch events. I can't test it on the device. Is this a known problem in the simulator?
    Thanks.

    Hi George,
    Thanks a lot for your quick response and jumping to help.
    I am so frustrated that I did not get touch event for the custom cell.
    I also tried your solution for a custom UIImageView, I put the codes of PhotoView.h, PhotoView.m and TestTouchAppDelegate.m here: Please help to look into it for me.
    // PhotoView.h
    // Molinker
    // Created by Victor on 6/18/08.
    // Copyright 2008 _MyCompanyName_. All rights reserved.
    #import <UIKit/UIKit.h>
    @interface PhotoView : UIImageView {
    CGPoint touchPoint1;
    CGPoint touchPoint2;
    @property (nonatomic) CGPoint touchPoint1;
    @property (nonatomic) CGPoint touchPoint2;
    @end
    // PhotoView.m
    // Molinker
    // Created by Victor on 6/18/08.
    // Copyright 2008 _MyCompanyName_. All rights reserved.
    #import "PhotoView.h"
    @implementation PhotoView
    @synthesize touchPoint1;
    @synthesize touchPoint2;
    - (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
    // Initialization code
    self.userInteractionEnabled = YES;
    return self;
    - (void)drawRect:(CGRect)rect {
    // Drawing code
    // Handles the start of a touch
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    UITouch *touch = [touches anyObject];
    touchPoint1 = [touch locationInView:self];
    // Handles the end of a touch event.
    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    UITouch *touch = [touches anyObject];
    touchPoint2 = [touch locationInView:self];
    if(touchPoint1.x>touchPoint2.x)
    //move Left
    NSLog(@"Move Left");
    if(touchPoint1.x<touchPoint2.x)
    //move Right
    NSLog(@"Move Right");
    - (void)dealloc {
    [super dealloc];
    @end
    // TestTouchAppDelegate.m
    // TestTouch
    // Created by Victor on 6/17/08.
    // Copyright _MyCompanyName_ 2008. All rights reserved.
    #import "TestTouchAppDelegate.h"
    #import "RootViewController.h"
    #import "PhotoView.h"
    @implementation TestTouchAppDelegate
    @synthesize window;
    @synthesize navigationController;
    - (id)init {
    if (self = [super init]) {
    return self;
    - (void)applicationDidFinishLaunching:(UIApplication *)application {
    // Configure and show the window
    //[window addSubview:[navigationController view]];
    UIImage *myImage= [UIImage imageNamed: @"scene1.jpg"];
    CGRect frame = CGRectMake (0, 20, 300, 400);
    PhotoView *myImageView1 = [[UIImageView alloc ] initWithFrame:frame];
    myImageView1.userInteractionEnabled = YES;
    myImageView1.image = myImage;
    [window addSubview:myImageView1];
    [window makeKeyAndVisible];
    - (void)applicationWillTerminate:(UIApplication *)application {
    // Save data if appropriate
    - (void)dealloc {
    [navigationController release];
    [window release];
    [super dealloc];
    @end
    Message was edited by: Victor Zhang

  • Reporting query - Cell editing

    Hi Experts !!
    I need some documents related to embedding multiple queries and formatting a workbook.
    I need more info on cell editing.
    Appreciate your help !!
    Thanks.

    hi yogita,
    Check the below link for checking the cell editing functionality
    [Cell editing|http://sap.seo-gym.com/celleditingBex.pdf]
    Regards
    KP
    have you tried to search in google of SDN before posting?

  • Keypressed event for a particular  edited cell of jtable

    hi friend,
    how to write the key pressed event for the edited cell of jtable which having focus on that particular cell.
    pls help me out.

    [http://catb.org/~esr/faqs/smart-questions.html]
    [http://mindprod.com/jgloss/sscce.html]
    db

  • How can i make perticular row or perticular cell Editable  of a JTable

    Dear al,
    can u help me by guiding me for the problem of...
    i am having a JTable, in which a (first)column of each row is having a checkbox field.
    If the checkbox is checked then and then i should able to modify the cells in that row where the checkbox is.
    I have created the table with AbstractTableModel of which the isCellEditable(int row, int col) method is overwriten. Whatever return value (true/false) reflects the perticular
    cells becomes editable/non-editable respectively.
    but at run time...(mean the table is created now) and now i want to make the cells editable/non-editable depending on the checkbox value...
    how can i implement it.........
    please suggest.........
    thank you.........

    here is the sample code from tutorial.......
    * TableRenderDemo.java requires no other files.
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    * TableRenderDemo is just like TableDemo, except that it explicitly initializes
    * column sizes and it uses a combo box as an editor for the Sport column.
    @SuppressWarnings("serial")
    public class TableRenderDemo extends JPanel {
         private boolean DEBUG = true;
         public TableRenderDemo() {
              super(new GridLayout(1, 0));
              JTable table = new JTable(new MyTableModel());
              // table.setEditingColumn(0);
              // table.editCellAt(0, 0);
              table.setPreferredScrollableViewportSize(new Dimension(500, 100));
              // Create the scroll pane and add the table to it.
              JScrollPane scrollPane = new JScrollPane(table);
              // Set up column sizes.
              initColumnSizes(table);
              // Fiddle with the Sport column's cell editors/renderers.
              setUpSportColumn(table, table.getColumnModel().getColumn(2));
              // Add the scroll pane to this panel.
              add(scrollPane);
          * This method picks good column sizes. If all column heads are wider than
          * the column's cells' contents, then you can just use
          * column.sizeWidthToFit().
         private void initColumnSizes(JTable table) {
              MyTableModel model = (MyTableModel) table.getModel();
              TableColumn column = null;
              Component comp = null;
              int headerWidth = 0;
              int cellWidth = 0;
              Object[] longValues = model.longValues;
              TableCellRenderer headerRenderer = table.getTableHeader()
                        .getDefaultRenderer();
              for (int i = 0; i < 5; i++) {
                   column = table.getColumnModel().getColumn(i);
                   comp = headerRenderer.getTableCellRendererComponent(null, column
                             .getHeaderValue(), false, false, 0, 0);
                   headerWidth = comp.getPreferredSize().width;
                   comp = table.getDefaultRenderer(model.getColumnClass(i))
                             .getTableCellRendererComponent(table, longValues, false,
                                       false, 0, i);
                   cellWidth = comp.getPreferredSize().width;
                   if (DEBUG) {
                        System.out.println("Initializing width of column " + i + ". "
                                  + "headerWidth = " + headerWidth + "; cellWidth = "
                                  + cellWidth);
                   // XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
                   column.setPreferredWidth(Math.max(headerWidth, cellWidth));
         public void setUpSportColumn(JTable table, TableColumn sportColumn) {
              // Set up the editor for the sport cells.
              JComboBox comboBox = new JComboBox();
              comboBox.addItem("Snowboarding");
              comboBox.addItem("Rowing");
              comboBox.addItem("Knitting");
              comboBox.addItem("Speed reading");
              comboBox.addItem("Pool");
              comboBox.addItem("None of the above");
              sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
              // Set up tool tips for the sport cells.
              DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for combo box");
              sportColumn.setCellRenderer(renderer);
         class MyTableModel extends AbstractTableModel {
              private String[] columnNames = { "First Name", "Last Name", "Sport",
                        "# of Years", "Vegetarian" };
              private Object[][] data = {
                        { "Mary", "Campione", "Snowboarding", new Integer(5),
                                  new Boolean(false) },
                        { "Alison", "Huml", "Rowing", new Integer(3), new Boolean(true) },
                        { "Kathy", "Walrath", "Knitting", new Integer(2),
                                  new Boolean(false) },
                        { "Sharon", "Zakhour", "Speed reading", new Integer(20),
                                  new Boolean(true) },
                        { "Philip", "Milne", "Pool", new Integer(10),
                                  new Boolean(false) } };
              public final Object[] longValues = { "Sharon", "Campione",
                        "None of the above", new Integer(20), Boolean.TRUE };
              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.
                   // return false;
                   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() + ")");
                   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("--------------------------");
         * Create the GUI and show it. For thread safety, this method should be
         * invoked from the event-dispatching thread.
         private static void createAndShowGUI() {
              // Create and set up the window.
              JFrame frame = new JFrame("TableRenderDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Create and set up the content pane.
              TableRenderDemo newContentPane = new TableRenderDemo();
              newContentPane.setOpaque(true); // content panes must be opaque
              frame.setContentPane(newContentPane);
              // Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args) {
              // Schedule a job for the event-dispatching thread:
              // creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();

  • IsCellEditable() to disable cell editing for specific columns

    Hello experts:
    My SSCCE for this question is at the below link:
    http://forum.java.sun.com/thread.jspa?threadID=5293914&messageID=10244030#10244030
    My question is how do I disable cell editing for all but the "Price" column of my table in the SSCCE. I tried adding the below lines of code right after creating the JTable. But get compilation errors.
    //Here is the block of code that I am trying to include.
         @Override                                                       
         public boolean isCellEditable(int row, int col) {     
         if (col == 7) {                                                  
                   return true;
              } else {
                   return false;
         } //Below is the method in detail03.java showing the block of code added
    private JScrollPane BuildEmptyTable() {
         model = new DefaultTableModel();
         model.addTableModelListener( this );
         model.setColumnIdentifiers(new String[] { "SKU","Qty", "Price"});
            tblDetailTest = new JTable(model);
         @Override                                                       
         public boolean isCellEditable(int row, int col) {     //     <----- I tried placing the
         if (col == 7) {                                        //                  the code block here
                   return true;
              } else {
                   return false;
         tblDetailTest.setRowHeight(20);
         tblDetailTest.setPreferredScrollableViewportSize(new Dimension(900, 100));
         JTableHeader tblHdr = tblDetailTest.getTableHeader();
         tblHdr.setBackground(Color.yellow);
         JScrollPane scrollPane = new JScrollPane(tblDetailTest);
         return scrollPane;
    }Can somebody please guide me? Thank you very much.

    oops!
    Sorry, my bad! I did not tell you what I tried. Following your suggestion, I made the following 2 changes to the code:
    In the method, BuildEmptyTable(), where I build the table structure, I have the following statement:
         tblDetail = new JTable(model){
    public boolean isCellEditable(int row, int col) {
           return col == 8;
    };And in a separate method after the table is populated with data, I have the below code:
         tblDetail.getModel().addTableModelListener(new TableModelListener() {
         public void tableChanged(TableModelEvent e) {
         if (e.getType() == TableModelEvent.UPDATE)
              int row = e.getFirstRow();
              int column = e.getColumn();
                 if (column == 8){
                   //code here
                   System.out.println("Updating item price!");
         }I do understand that the message gets displayed as many number of times equal to number of rows inserted into the table, because of the UPDATE event. But my problem is I do not know how to make a code change to do what I exactly want, as I have indicated in my previous note. Meaning I want the listener to be called only when the
    data in the editable cell changes.
    Thank You.

  • JTable Custom Cell  Event handling

    Hi,
    I have a column in JTable as image which is rendered by using custom cell renderer. I want to handle action event for the cell...
    I tried adding actionPerformed event for the button using which the image is rendered but the event is not triggered....
    Can you please tell me how to proceed with this
    Thanks,
    S.Anand

    I'm assuming you want to know when the user has clicked on a particular cell in the table. If so, add a MouseListener to the table then implement a MouseListener or one of the Mouse...Adapter classes with the method:
    public void mouseClicked(MouseEvent e)
        Point p = e.getPoint();
        int row = table.rowAtPoint(p);
        int col = table.columnAtPoint(p);
        // now do something according to the cell that was clicked

Maybe you are looking for

  • Budget in Training and Events

    Hello, I'm trying to configure the budget in training module. I will not have integration with Billing and Materials Management so I only want to create a Budget and have always the budget comparison, this means to compare the budgets created for eac

  • I DID A FULL ERACE OF MY PLAIN pALM pRE CELL PHONE NOT I CANT LOGIN

    Hello New guy here I have and currently own 2 palm pre PHONES one not working because of the same problem number 1 and 2 are the same let me explain This phone was acting up dots were doing as they choose to do and opening programs at will until it d

  • How to keep decimal in sql query

    Dear Expert, I try to do calculation in sql query, but it will automatically remove the decimal point. This is my query: SELECT 719 / 100 And i want a result = 7.19, but its not work. Its return 7. i did try to use, SELECT ROUND(719/100,2), but its n

  • Svrcfg show Job Server not running

    Hi, I am currently running Data Services 12.1.1.0 on Linux RH AS 4.6. I have noticed an issue and wondering whether there is something I am doing wrong. I installed DS and configured the JS. I have successfully started, stopped and started this again

  • SNote - Problems to implement SNotes

    Hi, I have heard about an intrastat problem in a system, after it has been transported to another system in a foreign country. Therefore I got the task to implement the Sap Note 533586, because in there the point 2 exactly describes the problems, we