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

Similar Messages

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

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

  • 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

  • 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

  • Different JComboBox in different Cells in a JTable

    Hi:
    I would like to make a JTable whose content would be several JBox with different values each one. That is to say, a double-column table with the value name in the first column and a range of possible values in the second column,
    Despite my efforts I was not able to do that. Every example that I found in the Web does not let different JComboBox per cell. They run with the same cell and values for each column.
    Can anybody help me?
    Thanks in advance.
    Carlos

    Here is an example that is based on camickr´s example:
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.*;
    import java.util.*;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.table.*;
    import javax.swing.JTable;
    import java.util.ArrayList;
    import javax.swing.DefaultCellEditor;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    public class TableCell extends JFrame
         JComboBox comboBox1 = new JComboBox();
         JComboBox comboBox2 = new JComboBox();
         JTable table;
         ArrayList<DefaultCellEditor> editors = new ArrayList<DefaultCellEditor>();
         TableCell()
              comboBox1.addItem("Tennis");
              comboBox1.addItem("Fotboll");
              comboBox1.addItem("Baseball");
              comboBox1.addItem("Handboll");
              comboBox2.addItem("USA");
              comboBox2.addItem("Brazil");
              comboBox2.addItem("Australia");
              comboBox2.addItem("China");
              comboBox2.addItem("Egypt");
              DefaultCellEditor dce1 = new DefaultCellEditor(comboBox1);
              DefaultCellEditor dce2 = new DefaultCellEditor(comboBox2);
              editors.add(dce1);
              editors.add(dce2);
              final JTable table = new JTable()
              { // anonym innerklass
                   private Class editingClass;
                   public TableCellRenderer getCellRenderer(int row, int column)
                        editingClass = null;
                        int modelColumn = convertColumnIndexToModel(column);
                        int modelRow = convertRowIndexToModel(row);
                        if (modelColumn == 1)
                             Class rowClass = getModel().getValueAt(row, modelColumn).getClass();
                             return getDefaultRenderer( rowClass );
                        else
                             return super.getCellRenderer(row, column);
                   public TableCellEditor getCellEditor(int row, int column)
                        editingClass = null;
                        int modelColumn = convertColumnIndexToModel(column);
                        int modelRow = convertRowIndexToModel(row);
                        if (modelColumn == 1)
                             if (modelRow == 5)     // cell number 5 in column 1 which is going to show the combobox
                                  return (DefaultCellEditor) editors.get(0);
                             if (modelRow == 6)     // cell number 6 in column 1 which is going to show the combobox
                                  return (DefaultCellEditor) editors.get(1);
                             else
                                  editingClass = getModel().getValueAt(modelRow, modelColumn).getClass();
                                  return getDefaultEditor( editingClass );
                        else
                             return super.getCellEditor(row, column);
              table.setModel(new javax.swing.table.DefaultTableModel
                   new Object [][]
                          {"String", "I'm a string"},
                        {"Date", new Date()},
                        {"Integer", new Integer(123)},
                        {"Double", new Double(123.45)},
                        {"Boolean", Boolean.TRUE},
                        {"Combobox 1", "COMBOBOX 1"},
                        {"Combobox 2", "COMBOBOX 2"}
                   new String [] { "Attribute", "Data" }
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              TableCell frame = new TableCell();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • 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 sorting JTable with custom cell editor

    Greetings,
    I have created a JTable with a JComboBox as the cell editor for the first column. However, I couldn't simply set the default cell editor for the column to be a JComboBox, since the values within the list were different for each row. So instead, I implemented a custom cell editor that is basically just a hashtable of cell editors that allows you to have a different editor for each row in the table (based on the ideas in the EachRowEditor I've seen in some FAQs - see the code below). I also used a custom table model that is essentially like the JDBCAdapter in the Java examples that populates the table with a query to a database.
    The problem comes when I try to sort the table using the TableSorter and TableMap classes recommended in the Java Tutorials on JTables. All of the static (uneditable) columns in the JTable sort fine, but the custom cell editor column doesn't sort at all. I think that the problem is that the hashtable storing the cell editors never gets re-ordered, but I can't see a simple way to do that (how to know the old row index verses the new row index after a sort). I think that I could implement this manually, if I knew the old/new indexes...
    Here's the code I use to create the JTable:
    // Create the Table Model
    modelCRM = new ContactTableModel();
    // Create the Table Sorter
    sorterCRM = new TableSorter(modelCRM);
    // Create the table
    tblCRM = new JTable(sorterCRM);
    // Add the event listener for the sorter
    sorterCRM.addMouseListenerToHeaderInTable(tblCRM);
    Then, I populate the column for the custom cell editor like this:
    // Add the combo box for editing company
    TableColumn matchColumn = getTable().getColumn("Match");
    RowCellEditor rowEditor = new RowCellEditor();
    // loop through and build the combobox for each row
    for (int i = 0; i < getTable().getRowCount(); i++) {
    JComboBox cb = new JComboBox();
    cb.addItem("New");
    //... code to populate the combo box (removed for clarity)
    rowEditor.add(i,new DefaultCellEditor(cb, i))); //TF
    } // end for
    matchColumn.setCellEditor(rowEditor);
    Any ideas how to do this, or is there a better way to either sort the JTable or use a combobox with different values for each row? Please let me know if more code would help make this clearer...
    Thanks,
    Ted
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class RowCellEditor implements TableCellEditor
    protected Hashtable editors;
    protected TableCellEditor editor, defaultEditor;
    public RowCellEditor()
    editors = new Hashtable();
    defaultEditor = new DefaultCellEditor(new JTextField());
    public void add(int row, TableCellEditor editor)
    editors.put(new Integer(row), editor);
    public Component getTableCellEditorComponent(JTable table,
    Object value,
    boolean isSelected,
    int row,
    int column)
    editor = (TableCellEditor) editors.get(new Integer(row));
    if (editor == null)
    editor = defaultEditor;
    return editor.getTableCellEditorComponent(table,
    value,
    isSelected,
    row,
    column);
    public Object getCellEditorValue() {
    return editor.getCellEditorValue();
    public boolean stopCellEditing() {
    return editor.stopCellEditing();
    public void cancelCellEditing() {
    editor.cancelCellEditing();
    public boolean isCellEditable(EventObject anEvent) {
    return true; //TF
    //return editor.isCellEditable(anEvent);
    public void addCellEditorListener(CellEditorListener l) {
    editor.addCellEditorListener(l);
    public void removeCellEditorListener(CellEditorListener l) {
    editor.removeCellEditorListener(l);
    public boolean shouldSelectCell(EventObject anEvent) {
    return editor.shouldSelectCell(anEvent);
    -------------------

    Well, I found a solution in another post
    (see http://forum.java.sun.com/thread.jsp?forum=57&thread=175984&message=953833#955064 for more details).
    Basically, I use the table sorter to translate the row index for the hashtable of my custom cell editors. I did this by adding this method to the sorter:
    // This method is used to get the correct row for the custom cell
    // editor (after the table has been sorted)
    public int translateRow(int sortedRowIndex)
    checkModel();
    return indexes[sortedRowIndex];
    } // end translateRow()
    Then, when I create the custom cell editor, I pass in a reference to the sorter so that when the getTableCellEditorComponent() method is called I can translate the row to the newly sorted row before returning the editor from the hashtable.

  • Help:JCombobox in table cell

    I have a column using combobox as cell editor in jtable, the combo box 's content is different based on the row user selects, for example, user selects the first row, the combo box will show selections" hi, hello", when user selected the second row, that row's combobox will show "where, what, why". How can I create individual comboxeditor or renderer for each cell in combo box column, so the contents of combo box will change based on the different rows. My old way is just to create a editor for the whole column, but based on the selection, remove all items in the combobox, and add new items in that combo box. The problem is when user first click the combo, all items disappear,the second click will show all newly added items,how can I show just all new items just by one click.
    Thanks a lot.

    I have a code that con solve your problem... It shows the contents of a cell as jcombobox...
    /*--- formatted by Jindent 2.1, (www.c-lab.de/~jindent) ---*/
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    * Class declaration
    * @author
    * @version %I%, %G%
    public class TableComboDemo extends JPanel {
         private JTable table;
         private int rows = 3;
         private int columns = 3;
         private int depth = 3;
         private String[][][] strings = new String[rows][columns][depth];
         private TableCellRenderer myRenderer = new MyComboRenderer();
         private TableCellEditor myEditor = new MyComboEditor();
         private TableModel myTableModel = new MyTableModel();
         * Constructor declaration
         * @see
         public TableComboDemo() {
              setupModel();
              table = new JTable() {
                   * Method declaration
                   * @param row
                   * @param column
                   * @return
                   * @see
                   public TableCellRenderer getCellRenderer(int row, int column) {
                        return myRenderer;
                   public TableCellEditor getCellEditor(int row, int column) {
                        return myEditor;
              table.setModel(myTableModel);
              this.add(new JScrollPane(table));
         * Method declaration
         * @see
         public void setupModel() {
              strings[0][0][0] = "a";
              strings[0][0][1] = "b";
              strings[0][0][2] = "c";
              strings[0][1][0] = "d";
              strings[0][1][1] = "e";
              strings[0][1][2] = "f";
              strings[0][2][0] = "g";
              strings[0][2][1] = "h";
              strings[0][2][2] = "i";
              strings[1][0][0] = "j";
              strings[1][0][1] = "k";
              strings[1][0][2] = "l";
              strings[1][1][0] = "m";
              strings[1][1][1] = "n";
              strings[1][1][2] = "o";
              strings[1][2][0] = "p";
              strings[1][2][1] = "q";
              strings[1][2][2] = "r";
              strings[2][0][0] = "j";
              strings[2][0][1] = "s";
              strings[2][0][2] = "t";
              strings[2][1][0] = "u";
              strings[2][1][1] = "v";
              strings[2][1][2] = "w";
              strings[2][2][0] = "x";
              strings[2][2][1] = "y";
              strings[2][2][2] = "z";
         * Method declaration
         * @param args
         * @see
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              frame.getContentPane().add(new TableComboDemo());
              frame.pack();
              frame.setVisible(true);
         * Class declaration
         * @author
         * @version %I%, %G%
         private class MyComboRenderer implements TableCellRenderer {
              private JComboBox combo;
              * Method declaration
              * @param table
              * @param value
              * @param isSelected
              * @param hasFocus
              * @param row
              * @param column
              * @return
              * @see
              public Component getTableCellRendererComponent(
                   JTable table,
                   Object value,
                   boolean isSelected,
                   boolean hasFocus,
                   int row,
                   int column) {
                   combo = new JComboBox((String[]) value);
                   return combo;
         * Class declaration
         * @author
         * @version %I%, %G%
         private class MyComboEditor extends DefaultCellEditor {
              private JComboBox combo;
              public MyComboEditor() {
                   super(new JComboBox());
              * Method declaration
              * @param table
              * @param value
              * @param isSelected
              * @param row
              * @param column
              * @return
              * @see
              public Component getTableCellEditorComponent(
                   JTable table,
                   Object value,
                   boolean isSelected,
                   int row,
                   int column) {
                   combo = new JComboBox((String[]) value);
                   return combo;
         * Class declaration
         * @author
         * @version %I%, %G%
         private class MyTableModel extends AbstractTableModel {
              * Method declaration
              * @return
              * @see
              public int getRowCount() {
                   return rows;
              * Method declaration
              * @return
              * @see
              public int getColumnCount() {
                   return columns;
              * Method declaration
              * @param row
              * @param column
              * @return
              * @see
              public Object getValueAt(int row, int column) {
                   return strings[row][column];
              * Method declaration
              * @param row
              * @param col
              * @return
              * @see
              public boolean isCellEditable(int row, int col) {
                   return true;
    }

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

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

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

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

Maybe you are looking for

  • Ipad In App purchases dont work.

    On my Ipad i download normally all my apps... but when i try do do an Inn app purchase the error "please contact Itunes support" appears!?? anyone knows this problem or can help me!?

  • My home button is not working but apple will not honor the limited warranty

    My home button on my ipod touch is not working but Apple will not honor the limited warranty because the corner glass is craked.  I have been using it cracked for months.  What is my legal recourse.  I think it is unfair!!!!!!

  • HT5361 i need to capitalize the i in my mail program using auto correct.

    However when I try to add it in the system preferences --> Language --> text -->  it says that i should have two characters.  I tried using a space but it doesn't work... what am i missing

  • Previous/Next View functionality is missing

    I do not see option to go back to the previous view in iPod version like in PC version. It is very inconvenient to jump to hiperlink and have no ability to return back. I found out that this question was already asked in http://forums.adobe.com/messa

  • Applying cache-config changes

    What is the recommended way to apply configuration changes to cache configurations? Let's say we decide to change a near-cache scheme to be tuned down from a 90 second expiry-delay to 15 seconds... I'm assuming that there are no auto-refresh mechanis