Editable JCombobox cell editor length limit

Hi All,
I have an editable JCombobox as a celleditor to one of the column in JTable, How do I limit the characters in the cell editor?
Thanks

A JComboBox uses a JTextField as it's cell editor. You should read up on how you would do this for a normal JTextField by using a custom Document:
http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html
Here's an example using JComboBox. I haven't tried it in a JTable but I assume it should work.
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.plaf.basic.*;
public class ComboBoxNumericEditor extends BasicComboBoxEditor
     public ComboBoxNumericEditor(JComboBox box)
          editor.setDocument( new NumericListDocument(box.getModel()) );
     public static void main(String[] args)
          String[] items = { "one", "two", "three", "four" };
          JComboBox list = new JComboBox( items );
          list.setEditable( true );
          list.setEditor( new ComboBoxNumericEditor( list ) );
          JFrame frame = new JFrame();
          frame.getContentPane().add( list );
          frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
          frame.pack();
          frame.setLocationRelativeTo( null );
          frame.setVisible( true );
     class NumericListDocument extends PlainDocument
          ListModel model;
          public NumericListDocument(ListModel model)
               this.model = model;
          public void insertString(int offset, String text, AttributeSet a)
               throws BadLocationException
               //  Accept all entries in the ListModel
               for (int i = 0; i < model.getSize(); i++)
                    Object item = model.getElementAt(i);
                    if (text.equals( item.toString() ))
                         super.insertString(offset, text, a);
                         return;
               //  Build the new text string assuming the insert is successfull
               String oldText = getText(0, getLength());
               String newText =
                    oldText.substring(0, offset) + text + oldText.substring(offset);
               //  Edit the length of the new string
               if (newText.length() > 2)
                    Toolkit.getDefaultToolkit().beep();
                    return;
               //  Only numeric characters are allowed in the new string
               //  (appending the "0" will allow an empty string to be valid)
               try
                    Integer.parseInt(newText + "0");
                    super.insertString(offset, text, a);
               catch (NumberFormatException e)
                    Toolkit.getDefaultToolkit().beep();
}

Similar Messages

  • JComboBox Cell Editor in JTable

    I've scouered the forums for an answer to my question, and while
    finding other valuable advice, I have yet to find an answer to my
    question. But first, a little description:
    I have a JTable consisting of 5 columns:
    col1= standard Object cell editor
    col2= JComboBox cell editor
    col3= JComboBox cell editor, values dependent on col2
    col4= JComboBox cell editor, values dependent on col3
    col5= JComboBox cell editor, values dependent on col4
    Data structure looks like this:
    col1= company object, containing vector of values for col2
    col2= lease object, containing vector of values for col3
    col3= well object, containing vector of values for col4
    col4= pump object, containing vector of values for col5
    col5= simply displayed.
    I have a JButton that adds a new row to the table via dialog, then menu
    options to add entries to the comboboxes/vectors. The kicker here is
    that everything is fine up until I've added a pump, and click the cell
    to view the entry. In my cellEditor class, I have a 'getSelected()'
    method that returns 'combobox.getSelectedIndex()'. When 'edittingStopped()'
    is thrown for any cell in this column, I get a null pointer in my
    getSelectedIndex() method of the lease combobox - only in this pump
    column. Even the part column works correctly. Code snips:
    public class MyApplication ... {
      private TableColumn leaseColumn;
      private TableColumn wellColumn;
      private TableColumn pumpColumn;
      private TableColumn partColumn;
      private LeaseDropDown leaseDropDown;
      private WellDropDown wellDropDown;
      private PumpDropDown pumpDropDown;
      private PartDropDown partDropDown;
      private int currentLease = 0;
      private int currentWell = 0;
      private int currentPump = 0;
      public MyApplication() {
        leaseColumn = pumpshopTable.getColumnModel().getColumn(1);
        leaseDropDown = new LeaseDropDown(companies);
        leaseColumn.setCellEditor(leaseDropDown);
        DefaultTableCellRenderer leaseRenderer =
          new DefaultTableCellRenderer();
        leaseRenderer.setToolTipText("Click for leases");
        leaseColumn.setCellRenderer(leaseRenderer);
        //... same for lease, well, pump, part ...
        leaseDropDown.addCellEditorListener(new CellEditorListener() {
          public void editingCanceled(ChangeEvent e) {
          } // end editingCanceled method
          public void editingStopped(ChangeEvent e) {
            updateCells();
          } // end editingStopped method
        }); // end addCellEditorListener inner class
        //.... same inner class for well, pump, part ...
      } // end MyApplication constructor
      public void updateCells() {
        currentLease = leaseDropDown.getSelectedLease();
        //... get current well, pump, part ...
        leaseDropDown = new LeaseDropDown(companies); // companies=Vector,col1
        leaseColumn.setCellEditor(leaseDropDown);
        //... same for lease, well, pump and part columns ...
      } // end updateCells method
    } // end MyApplication class
    public class LeaseDropDown extends AbstractCellEditor
        implements TableCellEditor {
      private Vector companiesVector;
      private JComboBox leaseList;
      public LeaseDropDown(Vector cVector) {
        companiesVector = cVector;     
      } // end LeaseDropDown constructor
      public Component getTableCellEditorComponent(JTable table,
          Object value, boolean isSelected, int rowIndex, int vColIndex) {
        Company thisCompany = (Company) companiesVector.get(rowIndex);
        Vector leasesVector = (Vector) thisCompany.getLeases();
        leaseList = new JComboBox(leasesVector);
        return leaseList;
      } // end getTableCellEditorComponent method
      public Object getCellEditorValue() {
        return leaseList.getSelectedItem();
      } // end getCellEditorValue method
      public int getSelectedLease() {
        JOptionPane.showInputDialog("Selected lease is: " +
          leaseList.getSelectedIndex());
        return leaseList.getSelectedIndex();          
      } // end getSelectedLease method
    } // end LeaseDropDown class... LeaseDropDown can be extrapolated to well, pump, and part,
    handing well the selected lease, handing pump the selected
    lease and well, handing part the selected lease, well and pump.
    I guess my question is how do I get the selected comboboxitem (I'd
    settle for the entire combobox if there's no other way) to fill in the
    next column? Why does the way I have it now work for the first 2 combobox
    columns and not the third?

    I'll try to provide more details.
    I use a JComboBox implementation as a cell in a JTable. The CombBox is editable . This is what I get when I try to type in something.
    java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
    at java.awt.Component.getLocationOnScreen_NoTreeLock(Component.java:1507)
    at java.awt.Component.getLocationOnScreen(Component.java:1481)
    at javax.swing.JPopupMenu.show(JPopupMenu.java:921)
    at javax.swing.plaf.basic.BasicComboPopup.show(BasicComboPopup.java:177)
    at javax.swing.plaf.basic.BasicComboBoxUI.setPopupVisible(BasicComboBoxUI.java:927)
    at javax.swing.JComboBox.setPopupVisible(JComboBox.java:790)
    at javax.swing.JComboBox.showPopup(JComboBox.java:775)
    I read some related bugs on the sun site but I am not sure if this is a bug and if it is then has it been fixed or work-around provided.
    any insights ??

  • Problem in JTable with a JComboBox cell editor

    Hi gurus,
    Please help! I am having a problem with a JTable that has a JComboBox cell editor. When the table is first loaded, the combo box column displays correct data. But whenever I click the combo box, the selection will be set to the first item in the combo box list once the popup menu pops up even before I make any new selection. It is very annoying.
    Here is how I set the cell editor:
    populateComboBoxModel(); // populate the combo box model.
    DefaultCellEditor cell_editor = new DefaultCellEditor(new JComboBox(
    combo_model));
    contrib_table.getColumnModel().getColumn(1).setCellEditor(
    cell_editor);
    I didn't set the cell renderer so I assume it is using the default cell renderer.
    Thanks !

    Not quite. The example doesn't have a different cell editor for each row of the table. I'm sure I must be missing something, bc I've found many references to the fact that this is possible to do. And I have most of it working. However, when I click on any given combobox, it automatically switches to the first value in the list, not the selected item. I've tried setting the selected item all over the code, but it has no effect on this behavior. Also, it only happens the first time I select a given cell. For example, suppose the first row has items A, B, and C, with B being the selected value. The table initially displays with B in this cell, but when I click on B, it switches to A when it brings up the list. If I select B, and move on to some other cell, and then go back and click on B again, it doesn't switch to A.
    There seems to be a disconnect between the values that I display initially, and the values that I set as selected in the comboboxes. Either that, or it behaves as though I never set the selected item for the combobox at all.
    Any help would be greatly appreciated.

  • JTable tab key navigation with JComboBox Cell Editors in Java 1.3 & 1.4

    Hello - this is one for the experts!
    I have a JTable which has an editable JComboBox as one of the cell editors for a particular column. Users must be able to navigate through the table using the tab key. After editing a cell a single tab should advance the cell selection to the next column and then the user should just be able to start typing to populate the cell.
    However, i've come across some really frustrating differences between the Swing implementation of JDK1.3.1_09 and JDK 1.4.2_04 which means this behaviour is very different between versions!....
    1. Editing Cells and then advancing to the next column using tab.
    Using standard cell editors (based around JTextFields) in 1.3.1 the user has to press tab twice to traverse to the next column after editing. However, in 1.4.2 a single tab key is enough to move to the next column after editing.
    2. Editable JComboBox editors and and advancing to the next column using tab.
    Using JDK 1.3.1, having entered some text in the editable combo it takes 2 tabs to transfer the selected cell to the next column. With 1.4.2 a single tab while editing the editable combo ends editing and transfers the selection out of the table completely?!?
    With these 2 issues I don't know how to make a single tab key reliably transfer to the next cell, between java versions. Can anyone please help me?!??!
    (i've attached test code below which can be run in both 1.3 and 1.4 and demonstrates the above behaviour.)
    package com.test;
    import java.awt.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class TableTest4 extends JFrame {
         private JTable table;
         private DefaultTableModel tableModel;
         public TableTest4() {
              initFrame();
          * Initialises the test frame.
         public void initFrame() {
              // initialise table
              table = new JTable(10, 5);
              tableModel = (DefaultTableModel) table.getModel();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              table.setRowHeight(22);
              JScrollPane scrollPane = new JScrollPane(table);
              getContentPane().add(scrollPane);
              JButton dummyBtn1 = new JButton("Dummy Button 1");
              JButton dummyBtn2 = new JButton("Dummy Button 2");
              // initialise frame
              JPanel btnPanel = new JPanel(new GridLayout(2, 1));
              btnPanel.add(dummyBtn1);
              btnPanel.add(dummyBtn2);
              getContentPane().add(btnPanel, BorderLayout.SOUTH);
              // set renderer of first table column to be an editable combobox
              JComboBox editableCombo = new JComboBox();
              editableCombo.setEditable(true);
              TableColumn firstColumn = table.getColumnModel().getColumn(0);
              firstColumn.setCellEditor(new DefaultCellEditor(editableCombo));
         public static void main(String[] args) {
              TableTest4 frame = new TableTest4();
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);

    Run the above code in 1.3 and 1.4 and you can see that after editing a cell, the tab key behaviour works differently between versions.
    I don't believe by adding a key listener to the cell editors will have the desired effect.
    I've read other posts and from what i've read it looks like the processKeyBinding method of the JTable can be overridden to manually handle key events.
    Has anyone done this to handle tab key presses so that the same java app running under 1.3 and 1.4 works in the same way ??? I would really appreciate some advice on this as its very frustrating !

  • Cell Editor to limit characters in jtable cell

    Hello Java Gods,
    Can anyone help me or write for me a custom cell editor/renderer to limit the max number of characters in a jtable cell to be 10? By this, I mean, the user should not be able to type more than 10 characters in this particular cell.
    Any help would be greatly appreciated. I have to hand in this code before this evening. So please please help me folks.
    Thanking you all in advance.
    Warm Regards,
    Java Newbie

    Try one of these CellEditors:
    class LimitedEditor extends DefaultCellEditor {
        public LimitedEditor() {
            super(new JTextField());
        public boolean stopCellEditing() {
            String value = ((JTextField) getComponent()).getText();
            if (!value.equals("")) {
                if (value.length() > 10) {
                    ((JComponent) getComponent()).setBorder(new LineBorder(Color.red));
                    JOptionPane.showMessageDialog(null, "String length cannot be bigger than 10");
                    return false;
            return super.stopCellEditing();
        public Component getTableCellEditorComponent(final JTable table, final Object value,
                final boolean isSelected, final int row, final int column) {
            JTextField tf = ((JTextField) getComponent());
            tf.setBorder(new LineBorder(Color.black));
            if (value == null) {
                tf.setText("");
            } else {
                tf.setText(value.toString());
            return tf;
    class LimitedEditor2 extends DefaultCellEditor {
        public LimitedEditor2() {
            super(new JTextField());
            JTextField tf = ((JTextField) getComponent());
            tf.setDocument(new PlainDocument() {
                public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
                    int len = getLength();
                    if (len + str.length() > 10) {
                        Toolkit.getDefaultToolkit().beep();
                    } else {
                        super.insertString(offs, str, a);
    }Usage example:
            TableColumn tc = table.getColumnModel().getColumn(1);
            tc.setCellEditor(new LimitedEditor2());]

  • JComboBox cell editor *Listener problem

    Hi all,
    I've setup a TreeTable with a JComboBox as a CellEditor for the second column.
    Everything works just fine, except for event handling on a column with a JComboBox as cell editor.
    In my case, the second column of the TreeTable represents the state of the activities. This state can be changed either programmatically or by user input. That is, my application can automatically change the state for some reason, or the user can select a new state for a particular activity with the mouse.
    What I need to achieve is to capture events generated only from the user.
    I've tried different solutions, adding ActionListener or ItemListener to the CellEditor, but they all capture events generated by the application in addition to those generated by the user of the application.
    Can someone please give me some advice in this matter?
    Xserty

    What I need to achieve is to capture events generated only from the user.If you called the JComboBox's dataModel.setSelectedItem method yourself, no event will be fired!Unfortunately, I'm not able to update the dataModel (directly) myself.
    I'm currently using the Creating TreeTables: Part 3; here's how it kinda works: my JTreeTable extends JTable. The JTreeTable has a model: TreeTableModel extends DefaultTreeModel implements InterfaceJTreeTableModel. In this model there are two methods implemented as following:
    public Object getValueAt(Object pParentNode, int pColumn) {
      MutableActivityNode activityNode = (MutableActivityNode) pParentNode;
      try {
        switch (pColumn) {
          case 0 :
            return activityNode.getName();
          case 1 :
            return activityNode.getState();
          case 2 :
            return new Boolean(activityNode.isMonitored());
          default :
            // do something
      } catch (SecurityException se) {
        // do something
      return null;
    public void setValueAt(Object pValue, Object pNode, int pColumn) {
      MutableActivityNode activityNode = (MutableActivityNode) pNode;
      try {
        switch (pColumn) {
          case 1 :
            activityNode.setState((String) pValue);
            break;
          case 2 :
            activityNode.setIsMonitored(((Boolean) pValue).booleanValue());
            break;
          default :
            // do something
      } catch (SecurityException se) {
        // do something
    }Once I create my JTreeTable (with a model), I set the editor of the second column of my JTreeTable to a JComboBoxCellEditor.
    As you may have noticed, all the information are stored in the node of the TreeTableModel and the information is displayed and set by the two methods above.
    Thank you anyways for the advice :))
    Have you any idea on how I could solve the problem in this case?
    Xserty

  • Problem using an editable JComboBox as JTable cell editor

    Hi,
    i have a problem using an editable JComboBox as cell editor in a JTable.
    When i edit the combo and then I press the TAB or ENTER key then all works fine and the value in the TableModel is updated with the edited one, but if i leave the cell with the mouse then the value is not passed to the TableModel. Why ? Is there a way to solve this problem ?
    Regards
    sergio sette

    if (v1.4) [url
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JTa
    le.html#setSurrendersFocusOnKeystroke(boolean)]go
    hereelse [url
    http://forum.java.sun.com/thread.jsp?forum=57&thread=43
    440]go here
    Thank you. I've also found this one (the first reply): http://forum.java.sun.com/thread.jsp?forum=57&thread=124361 Works fine for me.
    Regards
    sergio sette

  • JComboBox as a cell editor in JTable

    Hi,
    I've set one of my columns in my table to have a JComboBox as a cell editor. This is fine but my problem is that each row has different values in the JComboBox but when I update each row the column with the JComboBox they all end up with the same values.
    All help appreciated,
    Thanks,
    Lou
    // column with JComboBox
    TableColumn myCol = table.getColumnModel().getColumn(3);
    Vector comboValues = new Vector();
    JComboBox myCombo = null;
    for (int row = 0; row < tableModel.getRowCount(); row++)
    comboValues = new Vector();
    if (row == 0)
    // code here to add values to comboValues
    myCombo = (JComboBox) (((DefaultCellEditor) (table.getCellEditor(row, 3, .getComponent());
    myCombo = new JComboBox(comboValues);
    myCol.setCellEditor(new DefaultCellEditor(myCombo);
    tableModel.fireTableStructureChanged();
    tableModel.fireTableDataChanged();
    else
    // get differnent values for comboValues and update comboValues Vector
    myCombo = (JComboBox) (((DefaultCellEditor) (table.getCellEditor(row, 3, .getComponent());
    myCombo = new JComboBox(comboValues);
    myCol.setCellEditor(new DefaultCellEditor(myCombo);
    tableModel.fireTableStructureChanged();
    tableModel.fireTableDataChanged();

    Remember that you Table API specifies that each cell will use one instance of the specified editor...
    Think about that... the same editor is being used for each cell in that column... therefore, setting the
    data in the combobox et all will set it for that instance bveing used to edit the cell....
    Check out [url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#editrender]How to use Tables if in doubt...

  • Problem of JComboBox as cell editor in JTable

    Hi,
    I use JComboBox as cell editor in JTable. If the drop-down menu of the JComboBox out of the JTable area (as the editable cell is near the bottom of the JTable), the item in JComboBox can not be selected with mouse, in this situation there is no MouseEvent to be received in JTable. But it works when I use the keyboard to choose an item in JComboBox.

    Works fine for me.
    If you need further help then you will need to provide [url http://www.physci.org/codes/sscce.jsp]Simple Demo Code that demonstrates the problem.

  • Multicolumn JCombobox As a JTable Cell Editor

    My problem is 2 parts.
    1. MultiColumn JCombobox - I needed a combo box that could contain items which have an ID and a NAME. The NAME is displayed but value of the selected item is the ID. This seems to be a common problem. (DONE, I have figured this out).
    2. Now I have a column in a JTable that needs to use this new JCombobox as a CellEditor. The column data contains the IDs. When the user edits a cell in this column the JCombobox should display the available NAMEs to choose from and then store the ID of the selected NAME. (PARTIALLY done).
    My problem is that the table cell displays the ID at all times except when the user is editting it. The ID is really meaningless to the user. I would like the table cell to display the NAME of the selected ID after one is selected. However the ID is needed in the data as the unique identifier.
    I am not sure if anyone has tackled something like this before. Any help is appreciated.
    -Paul

    Create a custom renderer which will do the same as
    editor.
    regards,
    StasYou are correct Stas. Before I read your post this morning I had already started down that path. Then stopped to see if anyone had responded. This post assured me I was headed in the right direction. I created a new TableCellRenderer that takes the same ComboBoxModel that is used by the TableCellEditor/ComboBox. Then I can lookup the name based on the id and display the name in the cell. This one came to me in my sleep. Funny how that always works. Thanks,
    Paul

  • Theme Editor: where to change backgroundcolor of editable table cells?

    Hi all,
    I need to change the color of an editable table cell.
    I navigated to the theme editor --> tables.There is a section "Editable Tables". The preview shows an example with three columns and tree rows. I want to change the backgroundcolor of the cell in the first row, third column (in SAP standard it is lightgrey).
    The backgroundcolor of the rows beneath can be changed in section "Selected Cells", the backgroundcolor of the first two columns in the first row can be changed by "Background Color of Standard Table Cell" but I can't find the field where I can change the color of the last cell.
    Best regards,
    Sandra

    Hi,
    The blue color come from your definitions on "Labels and Fields" to read-only color of input field.
    Regards,
    F.F

  • Focus cell editor component of JTable when starting editing by typing

    Hello, everybody.
    We all know that the JTable component doesn't actually focus the actual cell editor component when editing is started by typing. But I need this functionality in an application of mine. So, I ask: is there a way to transfer focus to the editor component when editing is started by typing?
    Thank you.
    Marcos

    Well, I think that I've found it: JTable#setSurrendersFocusOnKeystroke.
    Marcos

  • Jcombobox as cell editor behaviour !

    1. on a normal combobox, when it got focus & i pressed up/down,
    the display will change depending on the selected item...
    but it's not when it used as jtable cell editor.
    is it possible to change that behaviour ?
    i want a normal combobox behaviour even when it used as cell editor
    2. i want to get combobox table cell editor by using double click,
    not single (the default)
    how can i do that ?
    sorry if this topic has been posted before, i found nothing on my search

    on a normal combobox, when it got focus & i pressed up/down,
    the display will change depending on the selected item...
    but it's not when it used as jtable cell editor.
    is it possible to change that behaviour ?
    i want a normal combobox behaviour even when it used as cell editora) You need to set celleditor property to false. ver overriding basisInit() method.
    this.putClientProperty("JComboBox.isTableCellEditor", Boolean.FALSE);b) You need to override custom keyboard action. Interhit from class and override the keyboard maps (Refer sample code below).
             * Adds keyboard actions to the JComboBox.  Actions on enter and esc are already
             * supplied.  Add more actions as you need them.
            protected void installKeyboardActions() {
                super.installKeyboardActions();
                ActionMap actionMap = SwingUtilities.getUIActionMap(comboBox);
                actionMap.put("togglePopup", new ToggleAction());
                actionMap.put("enterPressed", new EnterKeyAction());
                   actionMap.put("pageDownPassThrough", new CustomNavigationalAction(KeyEvent.VK_PAGE_DOWN));
                   actionMap.put("pageUpPassThrough", new CustomNavigationalAction(KeyEvent.VK_PAGE_UP));
                   actionMap.put("homePassThrough", new CustomNavigationalAction(KeyEvent.VK_HOME));
                   actionMap.put("endPassThrough", new CustomNavigationalAction(KeyEvent.VK_END));
            }With Regards,
    - Sushil

  • AutoComplete JComboBox As JTable cell editor

    Hello, when I try to use AutoComplete JComboBox as my JTable cell editor, I facing the following problem
    1) Exception thrown when show pop up. - Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
    2) Unable to capture enter key event.
    Here is my complete working code. With the same JComboBox class, I face no problem in adding it at JFrame. But when using it as JTable cell editor, I will have the mentioned problem.
    Any advice? Thanks
    import javax.swing.*;
    import javax.swing.JTable.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    * @author  yccheok
    public class NewJFrame extends javax.swing.JFrame {
        /** Creates new form NewJFrame */
        public NewJFrame() {
            initComponents();
                    /* Combo Box Added In JFrame. Work as expected. */
                    final JComboBox comboBox = new JComboBox();
                    comboBox.addItem("Snowboarding");
                    comboBox.addItem("Rowing");
                    comboBox.addItem("Chasing toddlers");   
                    comboBox.setEditable(true);
                    comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
                       public void keyReleased(KeyEvent e) {
                           if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                               System.out.println("is enter");
                               return;
                           System.out.println("typed");
                           comboBox.setSelectedIndex(0);
                           comboBox.showPopup();
                    getContentPane().add(comboBox, java.awt.BorderLayout.SOUTH);
        public JTable getMyTable() {
            return new JTable() {
                 Combo Box Added In JTable as cell editor. Didn't work as expected:
                 1. Exception thrown when show pop up.
                 2. Unable to capture enter key event.
                public TableCellEditor getCellEditor(int row, int column) {
                    final JComboBox comboBox = new JComboBox();
                    comboBox.addItem("Snowboarding");
                    comboBox.addItem("Rowing");
                    comboBox.addItem("Chasing toddlers");   
                    comboBox.setEditable(true);
                    comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
                       public void keyReleased(KeyEvent e) {
                           if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                               System.out.println("is enter");
                               return;
                           System.out.println("typed");
                           comboBox.setSelectedIndex(0);
                           comboBox.showPopup();
                    return new DefaultCellEditor(comboBox);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            jTable1 = getMyTable();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jScrollPane1.setViewportView(jTable1);
            getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
            pack();
        }// </editor-fold>                       
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        // End of variables declaration                  
    }

    You need to create a custom CellEditor which will prevent these problems from occurring. The explanation behind the problem and source code for the new editor can be found at Thomas Bierhance's site http://www.orbital-computer.de/JComboBox/. The description of the problem and the workaround are at the bottom of the page.

  • JTree: Cell Editor takes few click to start editing

    I have a JTree and have set the user defined renender and cell editor.
    However, user has to click continuously for some time to start the editing operation. How can I start the edit operation immediately after one click only.
    TIA
    Sachin

    ((DefaultCellEditor)myTable.getCellEditor()).setClickCountToStart(1);
    Remember that a click is a mouse press and release without moving the mouse.

Maybe you are looking for

  • Error when initializing input variable

    While trying to create a copy rule for the " assign " activity i get the "exception: could not retrieve message parts" has anybody seen this eorro before. Please help. Thanks

  • 10g to 11g migration

    steps to migrate from 10g to 11g in windows platform can anyone help me

  • In SharePoint Calendar lists, fields [Start Time] and [End Time] do not exist at the Site Column level.

    <header style="box-sizing:border-box;color:#777777;line-height:1;font-size:13px;padding-right:46px;margin-bottom:3px;font-family:'Helvetica Neue', arial, sans-serif;"> </header> I'm doing SP app development and have the following problem. I need to c

  • Java 1.4.2_04 Aggressive Heap on Windows 2000 Server

    Hi all I seem to be having trouble ith the JVM switch of -XX:+AggressiveHeap I have Tomcat 4.1 running with the following extra JVM options -server -XX:+AggressiveHeap -XX:+UseParallelGC -XX:+UseAdaptiveSizePolicy -XX:+DisableExplicitGC Its a quad pr

  • Stichwortsuche mit Adobe Bridge

    Ich arbeite mit Adobe Photoshop CS6 und dem zugehörigem Bildverwaltungstool Adobe Bridge. Meine Bilder habe ich in Bridge mit diversen Stichwörtern versehen und kann (in Bridge) über BEARBEITEN - SUCHEN Bilder (einzelne oder mehrere) mit speziellen S