Stopping cell editing in a JTable using a JComboBox editor w/ AutoComplete

Hi there! Me again with more questions!
I'm trying to figure out the finer parts of JTable navigation and editing controls. It's getting a bit confusing. The main problem I'm trying to solve is how to make a JTable using a combo box editor stop editing by hitting the 'enter' key in the same fashion as a JTextField editor. This is no regular DefaultCellEditor though -- it's one that uses the SwingX AutoCompleteDecorator. I have an SSCCE that demonstrates the issue:
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.AbstractCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableModel;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
public class AutoCompleteCellEditorTest extends JFrame {
  public AutoCompleteCellEditorTest() {
    JTable table = new JTable();
    Object[] items = {"A", "B", "C", "D"};
    TableModel tableModel = new DefaultTableModel(2, 2);
    table.setModel(tableModel);
    table.getColumnModel().getColumn(0).setCellEditor(new ComboCellEditor(items));
    getContentPane().add(table);
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    pack();
  private class ComboCellEditor extends AbstractCellEditor implements TableCellEditor {
    private JComboBox comboBox;
    public ComboCellEditor(Object[] items) {
      this.comboBox = new JComboBox(items);
      AutoCompleteDecorator.decorate(this.comboBox);
    public Object getCellEditorValue() {
      return this.comboBox.getSelectedItem();
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
      comboBox.setSelectedItem(value);
      return comboBox;
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      public void run() {
        new AutoCompleteCellEditorTest().setVisible(true);
}Problem 1: Starting to 'type' into the AutoCompleteDecorate combo box doesn't cause it to start editing. You have to hit F2, it would appear. I've also noticed this behaviour with other JComboBox editors. Ideally that would be fixed too. Not sure how to do this one.
Problem 2: After editing has started (say, with the F2 key), you may start typing. If you type one of A, B, C, or D, the item appears. That's all good. Then you try to 'complete' the edit by hitting the 'enter' key... and nothing happens. The 'tab' key works, but it puts you to the next cell. I would like to make the 'enter' key stop editing, and stay in the current cell.
I found some stuff online suggesting you take the input map of the table and set the Enter key so that it does the same thing as tab. Even though that's not exactly what I desired (I wanted the same cell to be active), it didn't work anyway.
I also tried setting a property on the JComboBox that says that it's a table cell editor combo box (just like the DefaultCellEditor), but that didn't work either. I think the reason that fails is because the AutoCompleteDecorator sets isEditable to true, and that seems to stop the enter key from doing anything.
After tracing endless paths through processKeyBindings calls, I'm not sure I'm any closer to a solution. I feel like this should be a fairly straightforward thing but I'm having a fair amount of difficulty with it.
Thanks for any direction you can provide!

Hi Jeanette,
Thanks for your advice. I looked again at the DefaultCellEditor. You are correct that I am not firing messages for fireEditingStopped() and fireEditingCancelled(). Initially I had copied the behaviour from DefaultCellEditor but had trimmed it out. I assumed that since I was extending AbstractCellEditor and it has them implemented correctly that I was OK. But I guess that's not the case! The problem I'm having with implementing the Enter key stopping the editing is that:
1) The DefaultCellEditor stops cell editing on any actionPerformed. Based on my tests, actionPerformed gets called whenever a single key gets pressed. I don't want to end the editing on the AutoCompleteDecorated box immediately -- I'd like to wait until the user is happy with his or her selection and has hit 'Enter' before ending cell editing. Thus, ending cell editing within the actionPerformed listener on the JComboBox (or JXComboBox, as I've made it now) will not work. As soon as you type a single key, if it is valid, the editing ends immediately.
2) I tried to add a key listener to the combo box to pick up on the 'Enter' key and end the editing there. However, it appears that the combo box does not receive the key strokes. I guess they're going to the AutoCompleteDecorator and being consumed there so the combo box does not receive them. If I could pick up on the 'Enter' key there, then that would work too.
I did more reading about input maps and action maps last night. Although informative, I'm not sure how far it got me with this problem because if the text field in the AutoCompleteDecorator takes the keystroke, I'm not sure how I'm going to find out about it in the combo box.
By the way, when you said 'They are fixed... in a recent version of SwingX', does that mean 1.6.2? That's what I'm using.
Thanks!
P.S. - Maybe I should create a new question for this? I wanted to mark your answer as helpful but I already closed the thread by marking the answer to the first part as correct. Sorry!
Edited by: aardvarkk on Jan 27, 2011 7:41 AM - Added SwingX versioning question.

Similar Messages

  • Stop cell editing

    I am facing bit common problem related to stop cell editing, here is code attached, when i do insert any string on cell and right after that clicking on save button, and i want to stop cell editing of table.
    and i know that this is easy to stop cell editing with line of code
    table.getCellEditor().stopCellEditing()but my problem is that i don't have access of this table on action performed of button. and that is not possible to access table here on action event. so please suggest me how to call stop cell editing when i move away with table.
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class TableEdit extends JFrame
       TableEdit()
          JTable table = new JTable(5, 5);
          table.setPreferredScrollableViewportSize(table.getPreferredSize());
          JScrollPane scrollpane = new JScrollPane(table);
          JPanel panel = new JPanel();
          panel.add(scrollpane);
          //getContentPane().add();
          JButton button = new JButton("Save");
          button.addActionListener(new ActionListener()
             @Override
             public void actionPerformed(ActionEvent e)
                // TODO Auto-generated method stub
          panel.add(button);
          getContentPane().add(panel);
       public static void main(String[] args)
          JFrame frame = new TableEdit();
          frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
    }

    but my problem is that i don't have access of this table on action performed of button. and that is not possible to access table here on action event. smake 'table' a field instead of local variable.
    public class TableEdit extends JFrame
         JTable table = new JTable(5, 5);
         .....Thanks!

  • I edit and rotate photos using MS Photo Editor. when open with Apple TV- photos still have 90 deg rotation. Why ?

    I edit and rotate photos using MS Photo Editor.
    When open with Apple TV- photos still have 90 deg rotation. Why ?

    Does this have anything to do with iPhoto for the Mac? If so please descrive what and exaclty wha tryou are doing
    LN

  • 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();

  • JTree stop cell editing on lost focus and scrollPathToVIsible behavior

    how can you make a Jtree that uses a DefaultTreeCellEditor stop editing when it loses focus to a component other than the
    cell editor's DefaultTextField component ?
    i had to use a custom TreeCellEditor and attach my focus listener to the DefaultTextField object and attach it also to the JTree object
              DefaultTreeCellEditor celEditor = new DefaultTreeCellEditor(containerTree,renderer)
                   @Override
                   public Component getTreeCellEditorComponent(JTree tree, Object value,
                                     boolean isSelected,
                             boolean expanded,
                             boolean leaf, int row) {
                        Component comp = super.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);
                        boolean found= false;
                        for(FocusListener f:editingComponent.getFocusListeners())
                             if(focusListener.equals(f))
                                  found=true;
                                  break;
                        if(!found)
                             editingComponent.addFocusListener(focusListener);
                        return comp;
    myTree.addFocusListener(focusListener);in JTable there's a property that you switch on/off which does exactly that, is there anything alike for JTree ?
    one more thing,after adding a new TreeNode to the JTree,i'm calling scrollPathToVisible(<path to the new node>),but for all the nodes i add except the first, the user object is not displayed,am i missing something? here's my code
              ActionListener actionListener = new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        DefaultTreeModel model = (DefaultTreeModel)containerTree.getModel();
                        int nodeCount=containerTree.getModel().getChildCount(root);
                        if(ae.getSource().equals(menuAdd))
                             DefaultMutableTreeNode newNode=new DefaultMutableTreeNode();
                             if(currentNode>0 && currentNode+1<nodeCount)
                                  model.insertNodeInto(newNode, root, currentNode+1);
                                  newNode.setUserObject("container #"+(currentNode+1));
                             else
                                  model.insertNodeInto(newNode, root, root.getChildCount());
                                  newNode.setUserObject("container #"+nodeCount);
                             TreePath path = new TreePath(newNode.getPath());
                                            // only works properly for 1st node,for the rest i have to
                                            // click on the new node to get the proper display
                             containerTree.scrollPathToVisible(path);
                        else if(nodeCount>=0 && currentNode!=0)
                             model.removeNodeFromParent((DefaultMutableTreeNode)model.getChild(root, currentNode-1));
              };

    i solved the second issue by selecting the new node and starting to edit it

  • Cell L&F of JTable

    hi ,
    I have a JTable contructed from DeaultTableModel and
    i have created a TableCellEditor which has a custom DefaultCellRenderer as its argument and
    added to the table
    THE PROBLEM is :
    When i edit in the table cell , the editable area of the cell becomes smaller compared to the area without a TableCellEditor, how can i change it ?
    and i want to change the border of the celll which is selected and its color
    Any Help ? Please.
    thanks.

    From one of the MS windows books.....Going by the books, eh?
    Well, apparently MS doesn't do so with Excel... Pressing space will simply trigger an edit!
    q1) JTable should have space bar handling out of the box?
    (space, CTRL+space, shift+space)
    I have not seen this raised as a bug.A bug, no... a feature, maybe. Anyway, JTable provides most of the features needed for creating a table -- it's far from perfect..... adding support for CTRL+SPACE and SHIFT+SPACE is not all that hard to do.
    q2) Should the enter key put an editable cell under edit and
    q3) if not should the first enter key stop cell editing and a second press activate the default buttonIMHO, a good answer to your question can be found by running MS Excel and see how it's done.
    The escape key will cancel editing of a cell that is under edit.and q4, q5
    It should, as in Excel. But then, in Lotus 1-2-3, first escape will clear the edit buffer (unless it's empty) and the second escape will cancel editing. Who'is more programmatically correct (I don't know)?
    ;o)
    V.V.

  • Disable cell editing

    Hi.
    Can I disable cell editing in a JTable without using a TableModel and still let the user click on different cells?
    /lars

    You can subclass JTable and override isCellEditable().

  • 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;
    };

  • Start or stop edit jtable cell editing

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

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

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

  • Directly enter edit mode of JTable cell

    Hi Everyone,
    On my UI, i am showing editable JTable. When I click on table's row / cell, it selects the row. Fine.
    But I want that it should directly enter edit mode of cell and the whole text is to be selected and highlighted and focussed.
    Thus, user can directly type the new text.
    Please suggest correct approach to handle this scenario.
    Thanks in advance.
    Girish Varde.

    Here is my attempt at solving this problem:
    **  For text selection you have two choices. Remove the "xxx" from either
    **  editCellAt() or prepareEditor() method.
    **  The difference is in how mouse double clicking works
    **  To place a cell directly into edit mode, use the changeSelection() method.
    **  Be aware this will generate a TableModelEvent every time you leave a cell.
    **  You can also use either of the above text selection methods.
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    public class TableEditCell extends JFrame
         public TableEditCell()
              String[] columnNames = {"Number", "Letter"};
              Object[][] data = { {"1", "A"}, {"2", "B"}, {"3", "C"} };
              JTable table = new JTable(data, columnNames)
                   //  Place cell in edit mode when it 'gains focus'
                   public void xxxchangeSelection(
                        int row, int column, boolean toggle, boolean extend)
                        super.changeSelection(row, column, toggle, extend);
                        if (editCellAt(row, column))
                             getEditorComponent().requestFocusInWindow();
                   //  Select the text when the cell starts editing
                   //  a) text will be replaced when you start typing in a cell
                   //  b) text will be selected when you use F2 to start editing
                   //  c) text will be selected when double clicking to start editing
                   public boolean xxxeditCellAt(int row, int column, EventObject e)
                        boolean result = super.editCellAt(row, column, e);
                        final Component editor = getEditorComponent();
                        if (editor != null && editor instanceof JTextComponent)
                             if (e == null)
                                  ((JTextComponent)editor).selectAll();
                             else
                                  SwingUtilities.invokeLater(new Runnable()
                                       public void run()
                                            ((JTextComponent)editor).selectAll();
                        return result;
                   //  Select the text when the cell starts editing
                   //  a) text will be replaced when you start typing in a cell
                   //  b) text will be selected when you use F2 to start editing
                   //  c) caret is placed at end of text when double clicking to start editing
                   public Component xxxprepareEditor(
                        TableCellEditor editor, int row, int column)
                        Component c = super.prepareEditor(editor, row, column);
                        if (c instanceof JTextComponent)
                             ((JTextField)c).selectAll();
                        return c;
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              TableEditCell frame = new TableEditCell();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              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.

  • Photoshop elements 13 editor has stopped working EVERYTIME i try to use smart detail brus.windows 7 home edition with plent of memeory and speed. any ideas WHY

    photoshop elements 13 editor has stopped working EVERYTIME i try to use smart detail brus.windows 7 home edition with plent of memeory and speed. any ideas WHY

    The faulting module is photoshop. Report below.
    Source
    Adobe Photoshop CC 2014
    Summary
    Stopped working
    Date
    2/2/2015 4:54 PM
    Status
    Report sent
    Description
    Faulting Application Path: C:\Program Files\Adobe\Adobe Photoshop CC 2014\Photoshop.exe
    Problem signature
    Problem Event Name: APPCRASH
    Application Name: Photoshop.exe
    Application Version: 15.2.2.310
    Application Timestamp: 5480338c
    Fault Module Name: Photoshop.exe
    Fault Module Version: 15.2.2.310
    Fault Module Timestamp: 5480338c
    Exception Code: c000001d
    Exception Offset: 00000000049de322
    OS Version: 6.3.9600.2.0.0.768.101
    Locale ID: 1033
    Additional Information 1: 8db4
    Additional Information 2: 8db473619c10c0c8b85ce99afe676ed8
    Additional Information 3: f06d
    Additional Information 4: f06da704bdd5338df2a8d09bde2244bb
    Extra information about the problem
    Bucket ID: 1fe6d1d4e5765bd348843b981b8ec4d2 (85990875000)

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

Maybe you are looking for

  • GE60 Apache Pro-003 mutes mic when S key pressed. Need recovery help...

    I don't actually believe that this is an issue with hardware as I have tried external keyboards and my friend pressed S using teamviewer and it still muted me.  I think the issue originated when I decided to install Ubuntu in front of the windows mai

  • How can A new Logic Studio (9.1.1) not be compatible with Lion?!

    ***! first Lion makes my 11 Rack's software inopperable, and now I finally got Logic Studio and it says I can't use Logic Pro because it's version 9.1.1. I was already having trouble, and after an our with apple phone support and a few more installin

  • Can't Start a Local Weblogic server.

    I have been trying for over a week now to figure this out. I have found no information on this issue and I don't know enough about WebLogic to find out what is going on. I have a local weblogic 10.3.5 server on my work laptop that I need to use to be

  • Save emails and attachments as PDF files

    I am wanting to save my emails and attachments as PDF files.  I have researched online and saw something through Adobe calle PDFMaker but I can't seem to find it.  I have downloaded the free trial of Acrobat DC but it doesn't seem to have that functi

  • Keyboard Shortcut conflict

    Hi- I'm working a lot with Flash 8. A common command is "Publish". The shortcut for this is Shift+F12...which is also the shortcut to launch Dashboard (in slow motion...no kidding). I went to System Prefs/Keyboard Shortcuts, found Dashboard and unche