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

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.

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

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

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

  • Customized JComboBox Editor for JTable

    Hi,
    I am new to swing development and have gotten my self stuck on an issue. Basically I have a JTable that is dynamically populated from the database, in which one of the columns has a customized JComboBox Renderer and Editor. The default values load up fine when the page loads up but when I selected a new value in the combo box and select a new row in the JTable, the combo box defaults back to the original value. How can I make sure that the new selection is maintain.
    Thanks, Anthony
    Here are my Driver, Renderer and Editor:
    excerpts from the Driver
    contract.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    keys = contractSelectedEvent.getKeys();
    String sql = contractSelectedEvent.getSchdSql(keys);
    table = contractSelectedEvent.getStatusTable(sql);
    table.setDefaultRenderer(CashFlow.class, new CashFlowRenderer());
    table.setDefaultEditor(CashFlow.class, new CashFlowEditor());
    public class CashFlowRenderer extends JComboBox implements TableCellRenderer {
    protected QueryComboBoxModel comboModel;
    /** Creates a new instance of CashFlowRenderer */
    public CashFlowRenderer() {
    super();
    comboModel = new QueryComboBoxModel("Select Ref_ID, Ref_Desc From Ref Where
    Ref_Typ_ID = 910 order by Ref_ID ");
    super.setModel(comboModel);
    public java.awt.Component getTableCellRendererComponent(javax.swing.JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus,
    int row,
    int column) {
    if(value == null) {
    return this;
    if(value instanceof CashFlow) {
    //set the cashflow equal to the value
    CashFlow cashFlow = new CashFlow(((CashFlow) value).getCashFlow());
    setSelectedItem(cashFlow);
    else {
    //default the cashflow
    CashFlow cashFlow = new CashFlow();
    setSelectedItem(cashFlow.getCashFlow());
    return this;
    public boolean isCellEditable() {
    return true;
    public class CashFlowEditor extends JComboBox implements TableCellEditor {
    protected transient Vector listeners;
    protected transient String originalValue;
    protected QueryComboBoxModel comboModel;
    /** Creates new CashFlowEditor */
    public CashFlowEditor() {
    super();
    comboModel = new QueryComboBoxModel("Select Ref_ID, Ref_Desc From Ref Where Ref_Typ_ID = 910 order by Ref_ID ");
    super.setModel(comboModel);
    listeners = new Vector();
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    if(value == null) {
    return this;
    if (value instanceof CashFlow) {
    setSelectedItem(((CashFlow)value).getCashFlow());
    else {
    CashFlow cashFlow = new CashFlow();
    setSelectedItem(cashFlow.getCashFlow());
    table.setRowSelectionInterval(row, row);
    table.setColumnSelectionInterval(column, column);
    originalValue = (String) getSelectedItem();
    return this;
    public void cancelCellEditing() {
    fireEditingCanceled();
    public Object getCellEditorValue() {
    return (String)getSelectedItem();
    public boolean isCellEditable(EventObject eo) {
    return true;
    public boolean shouldSelectCell(EventObject eo) {
    return true;
    public boolean stopCellEditing() {
    CashFlow cashflow = new CashFlow((String)getSelectedItem());
    setSelectedItem(cashflow.getCashFlow());
    fireEditingStopped();
    return true;
    public void addCellEditorListener(CellEditorListener cel) {
    listeners.addElement(cel);
    public void removeCellEditorListener(CellEditorListener cel) {
    listeners.removeElement(cel);
    protected void fireEditingCanceled() {
    setSelectedItem(originalValue);
    ChangeEvent ce = new ChangeEvent(this);
    for(int i = listeners.size(); i >= 0; i--) {
    ((CellEditorListener)listeners.elementAt(i)).editingCanceled(ce);
    protected void fireEditingStopped() {
    ChangeEvent ce = new ChangeEvent(this);
    for(int i = listeners.size() - 1; i >= 0; i--) {
    ((CellEditorListener)listeners.elementAt(i)).editingStopped(ce);

    First off, I wouldn't subclass JComboBox to create a custom renderer/editor. I would have a renderer/editor component that makes use of a JComboBox. But that is just me.
    In order for setSelectedItem to work, the items in your combo box have to compare against each other correctly with equals(). Since you are creating new instances, your objects (even though they contain the same data) are going to be different instances and aren't going to be considered equal. Write your own equals() method in your CashFlow object that tests for equality based on the actual values in the objects and you should be fine.

  • 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

  • Combobox Autocomplete editor inside Jtable cell

    I have a custom combobox editor which supports the autocomplete feature as follows:
    as soon as the user keys in any character, this editor searches for the item that starts with keyed in character. This item is displayed in the editor text field and the combobox popup is set to visible and the this item is set to selected.
    this editor works fine when standalone. but the popup fails to become visible when this combobox is used as an celleditor inside jtable. infact the focus is lost from the entire table.
    can anyone suggest the possible reason (and solution if possible).
    following are the code snippets for the same: -
         private TableCellEditor addCellEditor() {
              final JComboBox myJComboBox = new PIComboBox();
              myJComboBox.setModel(new DefaultComboBoxModel(// some data model //));
              //change the size of popup window
              BasicComboPopup comboPopup = null;
              for (int i=0, n=getUI().getAccessibleChildrenCount(myJComboBox); i<n; i++) {
                  Object component = getUI().getAccessibleChild(myJComboBox, i);
                  if (component instanceof BasicComboPopup) {
                   comboPopup = (BasicComboPopup) component;
                   break;
              if(null != comboPopup)
                  comboPopup.setLayout(new GridLayout(1,1));
                  comboPopup.setPopupSize(new Dimension(200, 150));
              myJComboBox.setEditable(true);
              myJComboBox.setEditor(new ComboBoxAutoCompleteEditor(myJComboBox, 3));
              myJComboBox.setUI(new ComboBoxAutoCompleteUI());
              TableCellEditor myCellEditor = new DefaultCellEditor(myJComboBox );
              return myCellEditor;
         public class ComboBoxAutoCompleteEditor extends BasicComboBoxEditor {
         public ComboBoxAutoCompleteEditor(PIComboBox comboBox, int maxLength) {
              super();
              this.comboBox = comboBox;
              this.maxLength = maxLength;
         @Override
         public Component getEditorComponent() {
              if(null == editorComponent)
                   editorComponent = new PITextField();
                   editorComponent.setBorder(null);
                   editorComponent.setMaxLength(maxLength);
                   editorComponent.setDocument(getDocument());
              return editorComponent;
         private ComboBoxAutoCompleteDocument getDocument()
              if(null == comboBoxAutoCompleteDocument)
                   comboBoxAutoCompleteDocument = new ComboBoxAutoCompleteDocument(
                             this.comboBox.getModel());
                   comboBoxAutoCompleteDocument.addDocumentListener(new ComboBoxDocumentListener());
              return comboBoxAutoCompleteDocument;
         private class ComboBoxDocumentListener implements DocumentListener {
              public void insertUpdate(DocumentEvent e) {
                   if (updatingSelection) {
                        return;
                   SwingUtilities.invokeLater(new ScrollHandler());
              public void removeUpdate(DocumentEvent e) {
              public void changedUpdate(DocumentEvent e) {
         private class ScrollHandler implements Runnable {
              private String scrollToString;
              private int scrollToRow;
              private ScrollHandler() {
                   try {
                        int length = getDocument().getLength();
                        String text = getDocument().getText(0, length);
                        scrollToRow = -1;
                        scrollToString = (String) comboBox.getSelectedItem();
                        ComboBoxModel model = comboBox.getModel();
                        int size = model.getSize();
                        for (int i = 0;  i < size; i++) {
                             String item = model.getElementAt(i).toString();
                             if (item.startsWith(text)) {
                                  scrollToString = item;
                                  break;
                             scrollToRow++;
                   } catch (BadLocationException ble) {
                        // TODO: handle
                        ble.printStackTrace();
              public void run() {
                   final int matchCount = getDocument()
                             .getCurrentMatchCount();
                   updatingSelection = true;
                   comboBox.setSelectedItem(scrollToString);
                   if (comboBox.isDisplayable())
                        comboBox.showPopup();
                   updatingSelection = false;
                   if (scrollToRow != comboBox.getItemCount() - 1) {
                        ComboBoxAutoCompleteUI ui = (ComboBoxAutoCompleteUI) comboBox
                                  .getUI();
                        JList popupList = ui.getPopupList();
                        int rowsToAdd = Math.min(comboBox.getMaximumRowCount(), comboBox
                                  .getItemCount()
                                  - scrollToRow - 1);
                        popupList.scrollRectToVisible(popupList.getCellBounds(
                                  scrollToRow + rowsToAdd, scrollToRow + rowsToAdd));
                   if (matchCount > 0) {
                        ((PITextField)getEditorComponent()).setSelectionStart(matchCount);
                        ((PITextField)getEditorComponent()).setSelectionEnd(
                                  getDocument().getLength());
         public class ComboBoxAutoCompleteUI extends BasicComboBoxUI {
             JList getPopupList() {
                 return popup.getList();
         public class ComboBoxAutoCompleteDocument extends PlainDocument {
         public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            currentMatchCount = getLength() + str.length();
            String currentText = getText(0, getLength());
            //search the matching string here
            offs = 0;
            remove(0, getLength());
            super.insertString(offs, str, a);
         **************

    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.

  • How to use JCombobox (using ComboboxModel) in JTable?

    I have a question first, let imagine that i have 2 tables: Location(IDLocation, Place), Employee(ID, Name, Location)
    And I get all data in Location table into ArrayList, then setup a model (that extends ComboboxModel) and use this arraylist.
    After that i get all data in Employee table into Arraylist, then setup a MyTableModel (that extends AbstractTableModel) and use this arraylist.
    I could setup combobox in Location column, but i just wonder that how do i know how many comboboxes i need?. And if i use one model for all of these comboboxed and when i change selected item in one combobox, it will change data in other comboboxes in other rows. :(
    Anybody helps me, please?

    you just need only one combobox as the editor for all cell in location column.
    because, initially, all the cell in location column is "rendered" as non-combobox, the combobox appears only when you edit one cell, so you use only one combobox for every edition of a cell (in location column).
    The way to do this is to setCellEditor of your JTable to (new DefaultCellEditor(editComboBox)), so that every time you click on a cell (in location column), the combobox appears and your selected value will be the new value in that cell, all you have to do is just set the CellEditor as combobox, java 's done the rest for you.
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#combobox : perfect in this situation
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    public class TableComboBox extends javax.swing.JFrame {
        public TableComboBox() {
         initComponents();
        private void initComponents() {
            scrollPane = new javax.swing.JScrollPane();
            myTable = new javax.swing.JTable();
            getContentPane().setLayout(new java.awt.FlowLayout());
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            // create a table
            myTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {"E01", "John Bolton", "Boston"},
                    {"E02", "Vannessa", "Ohio"},
                    {"E03", "Hellboy", "Alaska"}
                new String [] {
                    "ID", "Name", "Location"
            // create a combobox which model will be created from the database as the editor
            JComboBox locations = new JComboBox(new String[]{"Boston", "Ohio", "Alaska"});
            // create a default cell editor
            DefaultCellEditor editor = new DefaultCellEditor(locations);
            // set that cell editor as the location column cells editor (column number 2 is location column), then use setCellEditor() method
            myTable.getColumnModel().getColumn(2).setCellEditor(editor);
            scrollPane.setViewportView(myTable);
            getContentPane().add(scrollPane);
            java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-380)/2, (screenSize.height-117)/2, 380, 117);
        public static void main(String args[]) {
         java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
              new TableComboBox().setVisible(true);
        private javax.swing.JTable myTable;
        private javax.swing.JScrollPane scrollPane;
    }Edited by: bobbi2004 on Oct 28, 2008 9:59 AM

  • JComboBox remaining selected in JTable

    I have yet to figure out how to fix this problem. I have a JTable that is refreshed often with new data from a database (Next and Previous). If I select a JComboBox in the JTable, when I select Next or Previous the box remains selected and the value currently selected remains in there despite the new values from the DB. I know that the JComboBox refreshes correctly unless it is selected.
    How do you reset a JComboBox in a JTable so that you can update the JTable with the correct information without having to select something else?
    Note: When I hit the last, sometimes second to last, or a blank record, it becomes unselected and refreshes with the correct data. I am running on Win 2K.

    Not sure if I understand what you mean:
    I have yet to figure out how to fix this problem. I
    have a JTable that is refreshed often with new data
    from a database (Next and Previous). next/previous are buttons?
    If I select a
    JComboBox in the JTable, when I select Next or
    Previous the box remains selected the combo is still showing inside the table? And by select you mean pressing one of the button?
    If that's the situation then the table is still editing - by default it has a combo only as a cellEditor, not as a cellRenderer. So as long as the combo is showing the table did not stop editing - and while editing that particular value shown in the editor is never updated. And though the underlying tableModel is changed by some other event (like the db update) it is changed back to the value as shown in the editor when the editing is stopped some time later... confusing, isn't it?
    The way out is version dependent: safest because working in all jdk versions (except on 1.4.0 on the very first edit that ever happens on a table after startup) is to make sure that a possibly editing state of the table is stopped in your all your action handlers:
    actionPerformed(..) {
    if (table.isEditing()) {
    table.getCellEditor().stopCellEditing();
    // do your action
    That's undesirable for a couple of reasons (like f.i. the independent handlers need a reference back to table), so since 1.4.1 you can force the table to stop editing if the focus is transferred to the outside of the table. (it does not by default you have to set the client property "terminateEditOnFocusLost" to Boolean.TRUE)
    Greetings
    Jeanette

  • 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

  • How can I get the edited value from the editor in JTable

    I have a JTextField added as an editor to a cell in JTable.
    I value gets changed when I press enter.
    but in actionPerformed of the JTextField when I say
    String txtEditorValue = txtEditor.getText();
    I am getting the old value. How can I get the edited value? Thanks.

    Hi,
    I guess, your understanding of how JTable works together with its models is not good enough - for example the method getTableCellEditorComponent(...) of the TableCellEditor interface is used to get the component, that should be used as editing component - its second parameter is a value that should be used to setup the editing component - it is normally not the editing component itself.
    JTable uses an underlying TableModel to store the cell values - if you have edited a cell, JTable gets the value of the editing component by itself and stores it in the TableModel using its setValueAt(...) method. To retrieve this data you only need to query the TableModel using row and column of this cell as parameters
    say jt is your JTable, and row and column are the row and column of the cell - so to get the value, simply use
    Object obj = jt.getModel().getValueAt(row,column);
    if you know, that there is a String in this cell use
    String str = (String) jt.getModel().getValueAt(row,column);
    The editor component is used for the view of the JTable - you only want the data, which is stored in the model - you don't have to deal with the GUI components in this case.
    greetings Marsian

  • Set Maximum size for combobox editor in JTable

    Hi guys.
    I have a JTable with a custom JTextArea as editor for string datatypes.
    On the other hand, I have a combo editor too for some other columns of the table.
    My question is to know whether I can force the combox editor not to grow along with the text area.
    When I have a multiline text in a cell, I don 't want the combo box editor to fill the entire height of the row (the row height is continuously adjusted as user enter text into the text area cell editor), but to remain as big as just to render one line.
    Thanks.

    you know there's a swing forum, why not use it :-)
    As to your problem: the basicUI simply forces all editors to fit the cell size, returning more reasonable max-sizes for the combo wouldn't help. Way out might be to wrap into a panel with an appropriate layoutManager. Not entirely trivial, would expect some work ...
    Cheers
    Jeanette

Maybe you are looking for

  • JRE 1.4 US only - Error occurred during initialization of VM

    JAVA.EXE in JRE give that message Error occurred during initialization of VM with throwing NullPointerException This is NOT happening when using JRE international OR sdk - which is almost like JRE international but for some unknown reason WITHOUT the

  • Ace load balancing, inservice/no inservice serverfarms

    I've started working with an ACE load balancer and came across  something that just didn't add up to me. I can pull and put servers in  and out of rotation without a problem however when working with a  serverfarm or a group of servers I have to pull

  • CC 2014.2 - Preset migration

    I think I'm being blind here, so any pointers would be wonderful! If I go to C:\Users\NAME\Documents\Adobe\Adobe Media Encoder  I can see a folder for 7.0 and 8.0. Neither of these have what I need in them, as far as I can see.  I'm trying to find th

  • How do i get photos downloaded to my pc from iPod or iPad besides emailing them to myself?

    How can I get photos taken from my iPad or iPod to my PC besides e-mailing them to myself? Sorry if this is a silly question--I'm a newbie.

  • Audigy 4 - Microphone Recording is

    Hello everyone. I recently purchased and installed an Audigy 4 Pro. It is an awesome card, and everything is outstanding except for one major issue. As many of you know, the product comes with the 'Creative sound mixer'. In that mixer, on the extreme