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

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

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

  • Cell editors in JTable question

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

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

  • Cell editors in jtable

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

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

  • Tab transversal while using JTextArea as a JTable cell editor..

    I'm working on a project that will use a JTable with a JTextArea cell editor to create a chart for classroom scheduling. Searching on Google, I found a way to use a JTextArea as a cell editor and render the cell properly. However, when editing a cell, pressing the Tab key inserts a tab, rather than leaving the cell and going to the next one, as happens with just a regular JTable. In fact, none of the keyboard shortcuts that work on a JTable work once the JTextArea cell editor is used. Does anyone know of any way to resolve this? Below is some code I'm using to create a sample GUI, just to verify that I can do this. Another question is would it be easier to use a bunch of JLabels and JTextAreas, remove the padding from those JTextAreas, and try to allow for Tab transversals between stand-alone JTextAreas, rather than JTextAreas as JTable cell editors?
    Thanks!
    package edu.elon.table;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class GUI
         private JFrame frame;
         private String[] columnNames = {"Classroom", "8:00-9:10", "9:25-10:35",
              "10:50-12:00", "12:15-1:25", "1:40-2:50", "1:40-3:20 (MW)",
              "3:35-5:15 (MW)", "5:30-7:10 (MW)"};
         private Object[][] data = {columnNames,
              {"ALAM 201 (42)\nENG 110 LAB", "", "", "", "", "", "", "", ""},
              {"ALAM 202 (42)\nDP/DVD", "", "", "", "", "", "", "", ""},
              {"ALAM 203 (38)\nDP/DVD", "", "", "", "", "", "", "", ""},
              {"ALAM 205 (40)\n", "", "", "", "", "", "", "", ""},
              {"ALAM 206 (39)\nSINK, TV/VCR", "", "", "", "", "", "", "", ""},
              {"ALAM 207 (40+)\nDP/DVD", "", "", "", "", "", "", "", ""},
              {"ALAM 214 (38)\nTV/VCR", "", "", "", "", "", "", "", ""},
              {"ALAM 215 (42)\nTV/VCR", "", "", "", "", "", "", "", ""},
              {"ALAM 216 (42)\n", "", "", "", "", "", "", "", ""},
              {"ALAM 301 (40)\nTV/VCR", "", "", "", "", "", "", "", ""},
              {"ALAM 302 (38)\nDP/DVD", "", "", "", "", "", "", "", ""},
              {"ALAM 304 (35)\nFRENCH", "", "", "", "", "", "", "", ""},
              {"ALAM 314 (30)\nDP, PSY, COMPUTER ASSISTED", "", "", "", "", "", "",
              {"ALAM 315 (40)\nPC LAB, DP/DVD", "", "", "", "", "", "", "", ""}};
         private JTable table;
         public GUI()
              frame = new JFrame();
              table = new JTable(data, columnNames);
              table.setRowHeight(table.getRowHeight()*2);
              TableColumnModel cModel = table.getColumnModel();
              TextAreaRenderer renderer = new TextAreaRenderer();
              TextAreaEditor editor = new TextAreaEditor();
              for (int i = 0; i < cModel.getColumnCount(); i++)
                   cModel.getColumn(i).setCellRenderer(renderer);
                   cModel.getColumn(i).setCellEditor(editor);
              frame.setLayout(new GridLayout(1,0));
              frame.add(table);
              frame.pack();
              frame.setVisible(true);
    public static void main (String[] args)
    GUI gui = new gui();
    * Written by Dr. Heinz Kabutz, found through online newsletter via Google.
    class TextAreaRenderer extends JTextArea
    implements TableCellRenderer {
    private final DefaultTableCellRenderer adaptee =
    new DefaultTableCellRenderer();
    /** map from table to map of rows to map of column heights */
    private final Map cellSizes = new HashMap();
    public TextAreaRenderer() {
    setLineWrap(true);
    setWrapStyleWord(true);
    public Component getTableCellRendererComponent(//
    JTable table, Object obj, boolean isSelected,
    boolean hasFocus, int row, int column) {
    // set the colours, etc. using the standard for that platform
    adaptee.getTableCellRendererComponent(table, obj,
    isSelected, hasFocus, row, column);
    setForeground(adaptee.getForeground());
    setBackground(adaptee.getBackground());
    setBorder(adaptee.getBorder());
    setFont(adaptee.getFont());
    setText(adaptee.getText());
    // This line was very important to get it working with JDK1.4
    TableColumnModel columnModel = table.getColumnModel();
    setSize(columnModel.getColumn(column).getWidth(), 100000);
    int height_wanted = (int) getPreferredSize().getHeight();
    addSize(table, row, column, height_wanted);
    height_wanted = findTotalMaximumRowSize(table, row);
    if (height_wanted != table.getRowHeight(row)) {
    table.setRowHeight(row, height_wanted);
    return this;
    private void addSize(JTable table, int row, int column,
    int height) {
    Map rows = (Map) cellSizes.get(table);
    if (rows == null) {
    cellSizes.put(table, rows = new HashMap());
    Map rowheights = (Map) rows.get(new Integer(row));
    if (rowheights == null) {
    rows.put(new Integer(row), rowheights = new HashMap());
    rowheights.put(new Integer(column), new Integer(height));
    * Look through all columns and get the renderer. If it is
    * also a TextAreaRenderer, we look at the maximum height in
    * its hash table for this row.
    private int findTotalMaximumRowSize(JTable table, int row) {
    int maximum_height = 0;
    Enumeration columns = table.getColumnModel().getColumns();
    while (columns.hasMoreElements()) {
    TableColumn tc = (TableColumn) columns.nextElement();
    TableCellRenderer cellRenderer = tc.getCellRenderer();
    if (cellRenderer instanceof TextAreaRenderer) {
    TextAreaRenderer tar = (TextAreaRenderer) cellRenderer;
    maximum_height = Math.max(maximum_height,
    tar.findMaximumRowSize(table, row));
    return maximum_height;
    private int findMaximumRowSize(JTable table, int row) {
    Map rows = (Map) cellSizes.get(table);
    if (rows == null) return 0;
    Map rowheights = (Map) rows.get(new Integer(row));
    if (rowheights == null) return 0;
    int maximum_height = 0;
    for (Iterator it = rowheights.entrySet().iterator();
    it.hasNext();) {
    Map.Entry entry = (Map.Entry) it.next();
    int cellHeight = ((Integer) entry.getValue()).intValue();
    maximum_height = Math.max(maximum_height, cellHeight);
    return maximum_height;
    * Written by Dr. Heinz Kabutz, found through online newsletter via Google.
    class TextAreaEditor extends DefaultCellEditor
    public TextAreaEditor() {
         super(new JTextField());
    final JTextArea textArea = new JTextArea();
    textArea.setWrapStyleWord(true);
    textArea.setLineWrap(true);
    JScrollPane scrollPane = new JScrollPane(textArea);
    scrollPane.setBorder(null);
    editorComponent = scrollPane;
    delegate = new DefaultCellEditor.EditorDelegate() {
    public void setValue(Object value)
    textArea.setText((value != null) ? value.toString() : "");
    public Object getCellEditorValue()
    return textArea.getText();
    }

    Using the KeyEvent manager and playing around with the JTextArea, I was able to get a JTable using JTextAreas as the cell editors that worked very close to the way the regular JTable works. You have to hit Tab twice to shift focus to another cell, or hit Tab once and then an arrow key. Also, Alt-Enter will allow you to enter a cell for editing. All of the changes were made to the TextAreaEditor class, which should now read as follows:
    class TextAreaEditor extends DefaultCellEditor implements KeyListener
         private int lastKeyCode;
         public TextAreaEditor(final JTable table) {
              super(new JTextField());
              lastKeyCode = KeyEvent.CTRL_DOWN_MASK;
              final JTextArea textArea = new JTextArea();
              textArea.setWrapStyleWord(true);
              textArea.setLineWrap(true);
              textArea.addKeyListener(this);
              textArea.setFocusable(true);
              textArea.setFocusAccelerator((char) KeyEvent.VK_ENTER);
              JScrollPane scrollPane = new JScrollPane(textArea);
              scrollPane.setBorder(null);
              scrollPane.setFocusable(false);
              editorComponent = scrollPane;
              delegate = new DefaultCellEditor.EditorDelegate() {
                   public void setValue(Object value) {
                        textArea.setText((value != null) ? value.toString() : "");
                   public Object getCellEditorValue() {
                        return textArea.getText();
         public void keyTyped(KeyEvent ke)
              // TODO Auto-generated method stub
         public void keyPressed(KeyEvent ke)
              if (ke.getKeyCode() == KeyEvent.VK_TAB)
                   ke.consume();
                   KeyboardFocusManager.getCurrentKeyboardFocusManager()
                             .focusNextComponent();
                   return;
              if (ke.getKeyCode() == KeyEvent.VK_TAB && ke.isShiftDown())
                   ke.consume();
                   KeyboardFocusManager.getCurrentKeyboardFocusManager()
                             .focusPreviousComponent();
                   return;
              if ((lastKeyCode == KeyEvent.CTRL_DOWN_MASK) &&
                        (ke.getKeyCode() == KeyEvent.VK_ENTER))
                   ke.consume();
                   editorComponent.requestFocus();
              else
                   lastKeyCode = ke.getKeyCode();
         public void keyReleased(KeyEvent ke)
              // TODO Auto-generated method stub
         }

  • Small issue with custom table cell editor and unwanted table row selection

    I'm using a custom table cell editor to display a JTree. Thing i notice is that when i select a value in the tree pop-up, the pop-up closes (as it should) but then every table row, from the editing row to the row behind the pop-up when i selected the value becomes highlighted. I'm thinking this is a focus issue, but it thought i took care of that. To clairfy, look at this: Before . Notice how the "Straightening" tree item is roughly above the "Stock Thickness" table row? When i select Straightening, this is what happens to my table: After .
    My TreeComboBox component:
    public class TreeComboBox extends JPanel implements MouseListener {
        private JTextField itemField;
        private TreeModel treeModel;
        private ArrayList<ActionListener> actionListeners = new ArrayList<ActionListener>();
        private Object selectedItem;
         * Creates a new <code>TreeComboBox</code> instance.
         * @param treeModel the tree model to be used in the drop-down selector.
        public TreeComboBox(TreeModel treeModel) {
            this(treeModel, null);
         * Creates a new <code>TreeComboBox</code> instance.
         * @param treeModel the tree model to be used in the drop-down selector.
         * @param selectedItem tree will expand and highlight this item.
        public TreeComboBox(TreeModel treeModel, Object selectedItem) {
            this.treeModel = treeModel;
            this.selectedItem = selectedItem;
            initComponents();
         * Returns the current drop-down tree model.
         * @return the current <code>TreeModel</code> instance.
        public TreeModel getTreeModel() {
            return treeModel;
         * Sets the tree model.
         * @param treeModel a <code>TreeModel</code> instance.
        public void setTreeModel(TreeModel treeModel) {
            this.treeModel = treeModel;
         * Returns the selected item from the drop-down selector.
         * @return the selected tree object.
        public Object getSelectedItem() {
            return selectedItem;
         * Sets the selected item in the drop-down selector.
         * @param selectedItem tree will expand and highlight this item.
        public void setSelectedItem(Object selectedItem) {
            this.selectedItem = selectedItem;
            String text = selectedItem != null ? selectedItem.toString() : "";
            itemField.setText(text);
            setToolTipText(text);
         * Overridden to enable/disable all child components.
         * @param enabled flat to enable or disable this component.
        public void setEnabled(boolean enabled) {
            itemField.setEnabled(enabled);
            super.setEnabled(enabled);
        public void addActionListener(ActionListener listener) {
            actionListeners.add(listener);
        public void removeActionListener(ActionListener listener) {
            actionListeners.remove(listener);
        // MouseListener implementation
        public void mouseClicked(MouseEvent e) {
        public void mouseEntered(MouseEvent e) {
        public void mouseExited(MouseEvent e) {
        public void mousePressed(MouseEvent e) {
        public void mouseReleased(MouseEvent e) {
            showPopup();
        private void initComponents() {
            setLayout(new GridBagLayout());
            itemField = new JTextField();
            itemField.setEditable(false);
            itemField.setText(selectedItem != null ? selectedItem.toString() : "");
            itemField.addMouseListener(this);
            add(itemField, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0,
                    GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
        private void showPopup() {
            final TreePopup popup = new TreePopup();
            final TreeComboBox tcb = this;
            final int x = itemField.getX();
            final int y = itemField.getY() + itemField.getHeight();
            int width = itemField.getWidth() + popupButton.getWidth();
            Dimension prefSize = popup.getPreferredSize();
            prefSize.width = width;
            popup.setPreferredSize(prefSize);
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    popup.show(tcb, x, y);
                    popup.requestFocusInWindow();
        private void fireActionPerformed() {
            ActionEvent e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "TreeComboBoxSelection");
            for (ActionListener listener : actionListeners) {
                listener.actionPerformed(e);
        private class TreePopup extends JPopupMenu {
            private JTree tree;
            private JScrollPane scrollPane;
            public TreePopup() {
                initComponents();
                initData();
            private void initData() {
                if (treeModel != null) {
                    tree.setModel(treeModel);
            private void initComponents() {
                setFocusable(true);
                setFocusCycleRoot(true);
                tree = new JTree();
                tree.setRootVisible(false);
                tree.setShowsRootHandles(true);
                tree.setFocusable(true);
                tree.setFocusCycleRoot(true);
                tree.addTreeSelectionListener(new TreeSelectionListener() {
                    public void valueChanged(TreeSelectionEvent e) {
                        tree_valueChanged(e);
                scrollPane = new JScrollPane(tree);
                add(scrollPane);
            private void tree_valueChanged(TreeSelectionEvent e) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
                setSelectedItem(node.getUserObject());
                fireActionPerformed();
                this.setVisible(false);
    }My TreeComboBoxTableCellEditor:
    public class TreeComboBoxTableCellEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {
        protected TreeComboBox treeComboBox;
        protected ArrayList<CellEditorListener> cellEditorListeners = new ArrayList<CellEditorListener>();
        public TreeComboBoxTableCellEditor(TreeComboBox treeComboBox) {
            this.treeComboBox = treeComboBox;
            treeComboBox.addActionListener(this);
        public Object getCellEditorValue() {
            return treeComboBox.getSelectedItem();
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            treeComboBox.setSelectedItem(value);
            return treeComboBox;
        public void actionPerformed(ActionEvent e) {
            stopCellEditing();
    }Any thoughts?
    Edited by: MiseryMachine on Apr 3, 2008 1:21 PM
    Edited by: MiseryMachine on Apr 3, 2008 1:27 PM

    As I said, you have to have empty context elements before additional rows will be open for input.
    For instance if you want to start with 5 rows available for input do the following to your internal table that you will bind:
    data itab type standard table of sflight.
    do 5 times.
      append initial line to itab.
    enddo.
    context_node->bind_table( itab ).
    The other option if you need n number of rows is to add a button to the table toolbar for adding more rows. When this button is pressed, you add a new context element to the node - thereby creating a new empty row in the table.

  • Positioning custom cell editors

    I've got a custom cell editor that Im using to edit the cells of my JTable.
    I cant use a DefaultCellEditor, as my editor will contain a JTree.
    When I display the editor, I want to position it along-side the cell which was selected for editing.
    I can see methods in JTable to find the row/column at a given Point, but cant find any to get the location of a chosen row/column.
    Does anyone know if there is a way to do this?

    Here is some code that I used with a lot of debug messages. My editor is a table and the movement references was because the table could be off the parent table panel. If it was too far to the right, I wanted to move my popup table to the left to compensate.
         * Return the editor component to the table
         * @param table container for the editor
         * @param value value from the model
         * @param isSelected is the cell selected (has focus)
         * @param row of the cell
         * @param column of the cell
         * @return aLabel is used to provide visual feedback that the editor is
         * working
        public Component getTableCellEditorComponent(
            JTable table, Object value, boolean isSelected, int row, int column)
            logger.debug("PicklistEditor: getTableCellEditorComponent.value(" + value + ")");
            editingRow = row;
            editingColumn = column;
            dataEntryTable = table;
            dataEntryTable.setSurrendersFocusOnKeystroke(true);
            Rectangle tableRectangle = dataEntryTable.getBounds();
            int tableRightEdge = tableRectangle.x + tableRectangle.width;
            Point p = dataEntryTable.getLocationOnScreen();
            Rectangle r = dataEntryTable.getCellRect(row, column, true);
            Rectangle picklistRectangle = picklistFrame.getBounds();
            logger.debug("PicklistEditor: table.getBounds() = " + table.getBounds());
            logger.debug("PicklistEditor: tableRightEdge = " + tableRightEdge);
            logger.debug("PicklistEditor: picklistFrame.getBounds() = " + picklistFrame.getBounds());
            picklistFrame.setLocation(p.x + r.x, p.y + r.y + r.height);
            picklistFrame.setVisible(true);
            logger.debug(
                "PicklistEditor: picklistFrame.getLocationOnScreen() = " +
                picklistFrame.getLocationOnScreen());
            int picklistRightEdge = picklistFrame.getLocationOnScreen().x + picklistRectangle.width;
            int moveRightAmount = 0;
            if (picklistRightEdge > tableRightEdge)
                moveRightAmount = picklistRightEdge - tableRightEdge;
                picklistFrame.setLocation((p.x + r.x) - moveRightAmount, p.y + r.y + r.height);
            logger.debug("PicklistEditor: picklistRightEdge = " + picklistRightEdge);
            logger.debug("PicklistEditor: moveRightAmount = " + moveRightAmount);
            javax.swing.SwingUtilities.invokeLater(
                new Runnable()
                public void run()
                    editField.requestFocusInWindow();
            aLabel.setText("Editing...");
            logger.debug("PicklistEditor: editPanel.getBounds(" + editPanel.getBounds() + ")");
            logger.debug("PicklistEditor: editInputPanel.getBounds(" + editInputPanel.getBounds() +
            logger.debug("PicklistEditor: acceptEditFieldButton.getBounds(" +
                acceptEditFieldButton.getBounds() + ")");
            logger.debug("PicklistEditor: picklistScrollPane.getBounds(" +
                picklistScrollPane.getBounds() + ")");
            return aLabel;
    [\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Multi line issue in Table Cell Editor

    Hi,
    I am developing an occasionally connected application for handheld devices using NetWeaver Mobile 7.1. In one of the view, I have a table which display items information from the data source. In one of the column I need to display item description so I used TextEdit in the Cell Editor to display the information in multi line format and also wrapping is enabled.
    But during testing of the application the TextEdit control does not wraps the text and as well as only first line of TextEdit control is visible inside the table and rest of the rows are not visible because of table's row height is not adjusted to the TextEdit control. I couldn't find any option to vary the size of the row height of the table.
    Please suggest a solution to bring multi line display with in the table.
    Also, check out my other issue posted here.
    [Issue in wrapping of text in TextEdit control|Issue in wrapping of text in TextEdit control]
    Thanks in advance.
    Regards,
    DVR.
    Edited by: Vinodh Raj D on May 28, 2009 8:18 AM

    Hi Vinodh,
                   Mutliline text in a text view/edit control inside a table cell is not supported.
    You can view multiline text in a text view/edit as a seperate control inside a view. I think in case you want to see the whole address you can create a detail(s) view which can be navigated from the list (table) view.
    Regards,
    Nipun

  • Cannot tick checkbox cell editor in TreeNestedInTable UI

    Hi everyone,
    i have created a TreeNestedInTable UI using a Check Box cell editor.
    It all works fine except when I try to check on of the check boxes in the table it does not tick the box.  Instead, it highlughts the row.  I can, however, select multiple lines by using Ctrl+click.  This is not what I want however.
    Please advise if there is some setting that I am missing, perhaps.
    Many thanks.
    Christiaan

    Hi,
    check also this link
    http://help.sap.com/saphelp_nw04s/helpdata/en/9f/656442a1c4de54e10000000a155106/frameset.htm
    Matteo

  • Dropdowns as table cell editors

    Hi
    Does anyone know how to use dropdowns as table cell editors.  I need to create a table where some of the columns have dropdowns as the editor and some don't. 
    I can create the dropdown(by index) by binding a node to the table(the DD list) and binding a subnode-attribute as the text val but that gives me the same list in all rows.  As this is bound to the table and not the column all drop downs would have the same data in the DD list

    Here is what we do for dropdowns that need different values according to the selected row.
    1. Use a DropDownByKey as the table cell editor.
    2. Use the getModifiableSimpleValueSet() API call to modify the values attached to the dropdown on every row selection event.
    We don't have the case where you wouldn't actually have an editor, but you can disable the dropdown if the list is empty, which accomplishes the same effect.
    Beware that if your keys and values are different, the keys not in the current dropdown will not show up correctly on the other rows.

  • How to make JPanel as JTable Cell Editor (Urgent help needed)

    Hi!
    I want to make JPanel (with a JTextField, 3 JLabels and 1 JTextArea) as cell editor for one column. Can somebody help me on this?
    Does anybody have any sample code? I will greatly appreciate ur help.
    Thanks,
    Snehal

    Okie. In "How to use JTables" page found in the JAVA website (there is a link from the JTable section of the JAVA API documentation), there is a sample code for a sample color chooser. What this does is, adds a button with its action listener set to pop up a color chooser window. In this, rendering is still through a JLabel.
    This example would be of good help to you. Plus, this example gives me a feeling that what u ask is possible.

  • JPanel as a JTable Cell Editor

    I want to use a JPanel and as a JTable Cell Editor. The JPanel consists of a JTextField and a JButton. When I bring it up as an editor all works fine until I change the text field value and click on another line causing the editor to be stopped. Then my app seems to go into a processing frenzy which effectively stop me from doing anything else (the app has trouble repainting itself as well).
    I'm assuming I'm not passing an important message from the JPanel to the text field but am not sure. Has anyone had success in doing this? What am I missing?
    Thanks in advance,
    Phillip

    Looks like I was too quick off the draw in posting this.
    My problem was due to some old "expiremental" code that was processing key binding.
    Once I removed the unnecessary code all worked well.

  • 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

Maybe you are looking for

  • Broadvision Enterprise 5.5 on Solaris Intel?

    Hello, I hope you can help me on this: I'm in the process of procuring all the necessary compatibility info on Broadvision and Intel and came across Solaris 8, Intel... Has anyone attempted to run Broadvision 5.5 (Solaris) on Solaris 8, Intel? Any he

  • Best Settings for making a Secure, Reliable Disk Image?

    Hi guys! Can anybody direct me to the best settings that can be used to make a secure Disk image using the MacOS X disc utility? I wish to make my computer family friendly, yet keep my proffessional and private files secure/private and innaccesible t

  • Rational Rose product and Forte

    Has anyone used Rational Rose products and Forte? Could you post a short summary that explains how easy/hard it is to work with and whether or not the reverse engineering features work well? To unsubscribe, email '[email protected]' with 'unsubscribe

  • Fixing a 'line' in a VHS transfer

    I have a VHS I need to transfer to DVD and it has a white line running through parts of it (drop out or crease or something of that ilk). I'm wondering what the best way to fix it is. A search has come up with a few filters (such as one in the TMTS F

  • Mapping rows to Colums across two tables

    Hi All, I have a doubt as to how this could be done, could you please help me out with this one i have data in two tables Table 1 Prod_number          Refer_number C1               A1 C1               A2 C2               B1 C2               B2 C2