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 ??

Similar Messages

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

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

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

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

  • Using a JPanel as cell editor in JTable

    I have a composite component (JPanel that contains a JTextField and a
    JButton) that I would like to use as the a cell editor in a JTable.The JButton instantiates a UI editor component that I have designed. Example would be date editor for dates, tet editor for strings etc. This editor allows the user to select a date to populate the JTextField (the date may also be manually entered).
    I have no problem with the rendering of the component within the table.However, I would like for the JTextField embedded within the JPanel to receive focus and a visible caret, when using the tab key to navigate to the cell. After reading through some of the posts here , I was able to transfer the focus. But I dont see a visible caret. I am unable to edit. I have to click on the text box and then start typing. Its a great pain in the ass.
    I have a custom designed table and custom designed editor. Code is attached...
    <pre>
    protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,int condition, boolean pressed) {
    final int selRow = getSelectedRow();
    final int rowCount = getRowCount();
    final int selCol = getSelectedColumn();
    final EventObject obj = (EventObject) e;
    if (selRow == -1) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {           
    changeSelection(0, 1, false, false);
    editCellAt(0, 1, obj);
    boolean isSelected = false;
    if ((ks == KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0)) ||
    (ks == KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0))) {     
    if (selCol == 1) {
    isSelected= getCellEditor(selRow,selCol).stopCellEditing();
    targetRow = (selRow + 1) % rowCount;
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {           
    if (editCellAt(targetRow, 1, obj)) {
    changeSelection(targetRow, 1, false, false);
    getComponentAt(targetRow, 1).requestFocus();
    } else {
    getCellEditor(selRow, selCol).shouldSelectCell(obj);
    return super.processKeyBinding(ks,e,condition,pressed);
    </pre>
    Relevant code of my custom editor is below....
    public Component getTableCellEditorComponent(JTable table,
    Object value, boolean isSelected, int row, int column) {
    lastEditedRow = row;
    lastEditedCol = column;
    lastEditedTable = table;
    lastEditedValue = value;
    val = value;
    ((JTextField)editorComponent).
    setText(val == null ? "" : val.toString());
    setClickCountToStart(1);
    if (value instanceof CycCollectionChooserModel) {
    String collection = ((CycCollectionChooserModel)value).
    getCollection().cyclify();
    button.setVisible(EditorForCollectionMap.hasUIEditor(collection));
    button.setMargin (new Insets (1,1,1,1));
    button.setIconTextGap(0);
    buttonListener.model = (CycCollectionChooserModel)value;
    buttonListener.rowIndex = row;
    buttonListener.localTable = table;
    return panel;
    public boolean isCellEditable(EventObject evt) {
    if (evt instanceof MouseEvent) {
    int clickCount;
    clickCount = 1;
    return ((MouseEvent)evt).getClickCount() >= clickCount;
    return super.isCellEditable(evt);
    public boolean stopCellEditing() {   
    if (super.stopCellEditing()) {
    final int targetRow = (lastEditedRow+1)%lastEditedTable.getRowCount();
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {           
    lastEditedTable.changeSelection(targetRow, 1, false, false);
    lastEditedTable.getComponentAt(targetRow, 1).requestFocus();
    return true;
    return false;
    Does any one know why I am not able to see the caret? Any insights you have will be most welcome.
    Thanks in advance,
    Praveen.

    Almost solved the problem. Navigation through Tab key, up/ down arrow, Enter key works for text boxes. Navigation through Tab Key, Up/down arrow works for combo boxes. But for "Enter" key it doesnt. Changes in code ....
    (I have added a key listener to my editor class)
    <pre>
    protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,int condition, boolean pressed) {
    final int selRow = getSelectedRow();
    final int rowCount = getRowCount();
    final int selCol = getSelectedColumn();
    final EventObject obj = (EventObject) e;
    if (selRow == -1) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {           
    changeSelection(0, 1, false, false);
    editCellAt(0, 1, obj);
    boolean isSelected = false;
    if ((ks == KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0)) ||
    (ks == KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0)) ||
    (ks == KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,0))) {     
    if (selCol == 1) {
    final int targetRow = (selRow + 1) % rowCount;
    getCellEditor(selRow,selCol).stopCellEditing();
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    editCellAt(targetRow, 1, obj);
    changeSelection(targetRow, 1, false, false);
    getComponentAt(targetRow, 1).requestFocus();
    if ((ks == KeyStroke.getKeyStroke(KeyEvent.VK_UP,0))||
    (ks == KeyStroke.getKeyStroke(KeyEvent.VK_TAB,1))) {
    if (selCol == 1) {
    final int targetRow = (selRow - 1) % rowCount;
    getCellEditor(selRow,selCol).stopCellEditing();
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    editCellAt(targetRow, 1, obj);
    changeSelection(targetRow, 1, false, false);
    getComponentAt(targetRow, 1).requestFocus();
    return super.processKeyBinding(ks,e,condition,pressed);
    public class FactEditorComboBoxTableEditor extends DefaultCellEditor implements KeyListener{
    //// Constructors
    /** Creates a new instance of FactEditorComboBoxTableEditor. */
    public FactEditorComboBoxTableEditor(JComboBox comboBox) {
    super(comboBox);
    JTextField TF =(JTextField)((ComboBoxEditor)comboBox.getEditor()).
    getEditorComponent();
    TF.addKeyListener(this);
    public class FactEditorComboBoxTableEditor extends DefaultCellEditor implements KeyListener{
    //// Constructors
    /** Creates a new instance of FactEditorComboBoxTableEditor. */
    public FactEditorComboBoxTableEditor(JComboBox comboBox) {
    super(comboBox);
    JTextField TF =(JTextField)((ComboBoxEditor)comboBox.getEditor()).
    getEditorComponent();
    TF.addKeyListener(this);
    </pre>
    P.S : viravan, help me solve this problem and you will get the rest of the dukes LOL

  • JComboBox as editor in JTable

    Hi,
    I have used JComboBox as editor for cell in one of the columns in JTable.
    And to that JComboBox I have set the Editor by extending the BasicComboBoxEditor class in which I used JFormattedTextField as an editor. ie I have set the JFormattedTextField as an editor for JComboBox and then JComboBox as an editor for table column cell. Got it!
    Now here;s the problem, when the cell is editable and combobox is having focus by using down arrow button it shows the drop down list and i can scroll it by pressing down arrow button. Now if i hit enter button it is not selecting the value and does nothing. Is there any techinical reason for this.
    I want that when I press Enter or tab after scrolling using down arrow button it should select currenlty highlited item. Rest of the work is done.
    Thanks and regards
    Nilesh

    Hello there
    I had a similar problem and I spent ages trying to figure it out. I take it the cell you are trying to edit is already empty. What it is, while you have a cell editor on the cell in question, you dont have a cell renderer which is responsible for actually drawing the selected item in the cell once the editing combobox has closed. The way I found around this problem was to fill the cells of the table with some default data when the table is initalised, this meant that a suitable renderer for the type of data I was trying to display was automatically assigned.
    Hope this helps

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

  • 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

  • Cell editors in JTable question

    My table has cell editors in it.
    I want to add focusLost and focusGained on these editor components. How can I do this? I want to get the editor component and add these? In which method I could use to get the editor and addFocusListener to to this editor.
    Thanks.

    void table_focusGained(FocusEvent e) {
    // do something here. For example:
    table.setRowSelectionAllowed(true);
    if (table.getRowCount() > 0) {
    if (table.getSelectedRowCount() <= 0) {
    table.setRowSelectionInterval(0, 0);
    void table_focusLost(FocusEvent e) {
    // do something here

  • Cell editors in jtable

    Hi!
    I have a jtable, composed of two columns. One of this columns has a DefaultCellEditor (a JTextField). Is there any way to make the table display values (strings) in different colors (one color for each row of the table), in this column?
    Thanxs in advance,
    Meli

    I am assuming that you want different colors while editing the cell only.
    You can do this by using your own cellrenderer. Create a sub-class of DefaultCellEditor. Override getTableCellEditorComponent method. In this you can return a JTextField component with different background color depending on the selected row.

  • 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

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

  • JTable custom cell editor focus problem

    Hi I have created a JTable (using Java 1.4.2) and have three cell Editors, one is a JFormattedTextField, one is a JComboBox and one is a custom cell editor.
    When I press tab I can select the cell with the JFormattedTextField and when I start typing the JFormattedTextField accepts my input and it is displayed in the cell. This is the type of behaviour I would like but it does not seem to work for my other 2 cell editors:
    When I tab to the JComboBox cell I can see that the cell is selected but typing or using the arrow keys does not allow me to select a new value in the JComboBox. (I have also tried typing space or enter to activate the JComboBox whilst the cell is selected.) The only ways to select a new value at the moment is to first click on the cell with the mouse and then use the keyboard to select a new value. It is like the actual JComboBox is not receiving the focus? Does anyone know how to solve this problem?
    I also seem to have the same problem with my custom cell editor. My custom editor is a JPanel which contains JFormattedTextField again I can tab to the cell and see that it is selected but to activate the JFormattedTextField I have to actually select it with the mouse.
    I have been stuck on this for some time so if any one has any suggestions they would be much appreciated !

    Hi I have created a JTable (using Java 1.4.2) and have three cell Editors, one is a JFormattedTextField, one is a JComboBox and one is a custom cell editor.
    When I press tab I can select the cell with the JFormattedTextField and when I start typing the JFormattedTextField accepts my input and it is displayed in the cell. This is the type of behaviour I would like but it does not seem to work for my other 2 cell editors:
    When I tab to the JComboBox cell I can see that the cell is selected but typing or using the arrow keys does not allow me to select a new value in the JComboBox. (I have also tried typing space or enter to activate the JComboBox whilst the cell is selected.) The only ways to select a new value at the moment is to first click on the cell with the mouse and then use the keyboard to select a new value. It is like the actual JComboBox is not receiving the focus? Does anyone know how to solve this problem?
    I also seem to have the same problem with my custom cell editor. My custom editor is a JPanel which contains JFormattedTextField again I can tab to the cell and see that it is selected but to activate the JFormattedTextField I have to actually select it with the mouse.
    I have been stuck on this for some time so if any one has any suggestions they would be much appreciated !

  • JTable - Custom cell editor lossing commit

    Hello,
    I have a custom cell editor and a default renderer assigned to a specific cell in my table...
    I have the following problem :
    If i change the value of cell 'c1' from value 'v1' to 'v2' and press enter and go to another cell the value in 'c1' is rendered correctly as 'v2'
    Hoever if i change the value of cell 'c1' from 'v1' to 'v2' and simply click over to another cell the value in 'c1' stays rendered as 'v1'
    Question : Is there ANY way to mimic the behavior of the user pressing enter in my custom cell editor when a user simply selects another cell, i guess on loss of focus or something..
    This is the last problem i have on the current project i am on and its very annoying.
    Thanks in advance, any help appreciated..
    -Alan

    I have the same problem using a custom Date/Time Picker Object (which extends JComboBox) as an editor within a table cell. For simplicity sake, I am posting code using only the base editable JComboBox, but it exhibits the same symptoms. If you enter a value in the TextField portion of the ComboBox and Tab, your value remains the same. If you enter a value in the TextField portion of the ComboBox and click in another cell, the value returns to the previous value (before editing began).
    import java.awt.*;                                                  // BorderLayout
    import javax.swing.*;                                               // JTable, JFrame
    import javax.swing.table.*;                                         // DefaultTableModel
    public class Tester extends JFrame
      public static void main(String[] args)
        Tester test = new Tester();
      public Tester()
        String[] values = {"Test", "Values"};
        JComboBox combo = new JComboBox(values);
        combo.setEditable(true);
        DefaultCellEditor editor = new DefaultCellEditor(combo);
        JTable table = new JTable(2, 3);
        table.getColumn(table.getColumnName(0)).setCellEditor(editor);
        JScrollPane scroll = new JScrollPane(table);
        getContentPane().add(scroll, BorderLayout.CENTER);
        pack();
        setVisible(true);
    }

Maybe you are looking for

  • PO report for a particular department

    Hi We would like to run a report of all PO's of the technical department from 01-01-2007 till now and with their costs and the grand total. This report should list: -          PO number (only for PM PO's) -          Cost centre -          Item descri

  • Font Book 2.0.3

    I am trying to find out if my Font Book has Crashed. My Illustrator all of a sudden would stop responding, uninstalled it and reinstalled. But I get the following error when I tried to create a PDF: The font Futura could not be imbedded in the PDF do

  • How users access the sites in NTLM authentication

    Hi,   For kerberos when users try to access the site actually they able to access the site through the app-pool account of the web app for which we register the SPN. But for NTLM how that works. When a user tries to access the site in NTLM does it go

  • Internet/Mail issues

    I have searched through this (and other) forums but haven't been able to find an answer. I have just upgraded to ADSL2 in australia. Here are my issues. I can browse (Safari 2.0.4 and 3beta) bou only SOME pages. Even www.apple.com.au will only load t

  • Data is not showing in print preview

    Hi i am trying to take the printout of service purchase order,but before saving i am not getting any content in the printout preview,but after saving i am getting the content,is there any thing do from functional side thanks vivek