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

Similar Messages

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

  • Editable JComboBox in JTable

    There is a bug in Jdk1.5 (bug#4684090) - When TAB out from Editable Jcombobox in JTable, the focus is moved to outside JTable instead of next cell.
    What is the best workaround for thsi bug.
    Thanks,
    VJ

    I was using java 1.5.0_06 in my application and I had this problem
    When I upgraded to java 1.6.0_01, I no longer had this issue.
    This seems to be a bug in 1.5 version of Java that has been fixed in 1.6
    thanks,

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

  • Custom JTable cell editor problem

    I have a custom JTable cell editor which is a JPanel with 2 JtextFields, One for a name, the other for a data value. My problem lies in when the the cell is selected and then the user start typing. The JTextfield outline shows up, but there is no carat. I can only edit the cell when I click the mouse in it again. I have my isCellEditable method set to only allow editing on 2 mouse clicks, but I did try it with just returning true and had the same problem. Please help.
    Code:
    class cellValue {
    String name;
    String data;
    Color nameColor;
    Color dataColor;
    Font font;
    public cellValue(String n, String d, Color nC, Color dC, Font ff){
    name = n;
    data = d;
    nameColor = nC;
    dataColor = dC;
    font = ff;
    } //end class
    public class TextFieldCellEditor extends JPanel implements TableCellRenderer, TableCellEditor{
    private EventListenerList listenerList = new EventListenerList();
    private ChangeEvent event = new ChangeEvent(this);
    private cellValue s;
    private int e_row=0;
    private int e_col=0;
    private JTextField ta;
    private JTextField tb;
    public TextFieldCellEditor() {
    setLayout(new GridBagLayout());
    ta = new JTextField();
    tb = new JTextField();
    tb.setHorizontalAlignment(SwingConstants.RIGHT);
    add(ta, new GridBagConstraints(0,0,1,1,0.6,0.0,java.awt.GridBagConstraints.WEST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    add(new JLabel(" "),new GridBagConstraints(1,0,1,1,0.1,0.0,java.awt.GridBagConstraints.WEST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    add(tb, new GridBagConstraints(2,0,1,1,0.3,0.0,java.awt.GridBagConstraints.EAST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    } //end init
    public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected,
    boolean hasFocus,int row, int column) {
    s = (cellValue)value;
    e_row = row;
    e_col = column;
    ta.setText(s.name);
    tb.setText(s.data);
    ta.setFont(s.font);
    tb.setFont(s.font);
    ta.setForeground(s.nameColor);
    tb.setForeground(s.dataColor);
    setForeground(table.getForeground());
    setBackground(table.getBackground());
    ta.setBackground(table.getBackground());
    tb.setBackground(table.getBackground());
    ta.setCaretColor(Color.WHITE);
    tb.setCaretColor(Color.WHITE);
    return (JComponent)(this);
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    return (getTableCellRendererComponent(table, value,isSelected, true, row, column));
    public boolean isCellEditable(EventObject e) {
    if (e instanceof MouseEvent) {
    return ((MouseEvent)e).getClickCount() >= 2;
    } return true;
    // return true;
    public boolean shouldSelectCell(EventObject anEvent) {
    return (true);
    public void cancelCellEditing() {
    public boolean stopCellEditing() {
    fireEditingStopped();
    return (true);
    public Object getCellEditorValue() {
    return (ta.getText());
    public void addCellEditorListener(CellEditorListener l){
    try {
    SwingUtilities.invokeLater(
    new Runnable() {
    public void run() {requestFocus();}
    } catch (Exception e) {};
    listenerList.add(CellEditorListener.class, l);
    public void removeCellEditorListener(CellEditorListener l) {
    listenerList.remove(CellEditorListener.class, l);
    protected void fireEditingStopped(){
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2)
    ((CellEditorListener)listeners[i+1]).editingStopped(event);
    protected void fireEditingCanceled() {
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2)
    ((CellEditorListener)listeners[i+1]).editingCanceled(event);
    } //end class

    Thanks again for the repley.
    I tried removing the celleditorlistener and using the setSurrenderFocusOnKeystroke, but it did not work. The textfield is editable;
    I did change:
    public void addCellEditorListener(CellEditorListener l){
    try {
    SwingUtilities.invokeLater(
    new Runnable() {
    public void run() {ta.requestFocus();}
    } catch (Exception e) {};
    listenerList.add(CellEditorListener.class, l);
    }This allows the first textfield to request focus and this seems to work. But when I highlight a cell, then start typing, the first character I type puts me into the editor, but it is lost. Example:
    I type hello
    and get ello in the cell. Then when I press enter the input is excepted and the selection goes to the next cell, but I cannot move the Highlight cursor at all, seems locked. The only way I can continue to the next cell is to use the mouse.
    You said you had a cell editor working. Would you care to share as an example. This is killing me to get this to work properly.
    Thanks again
    Dave

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

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

  • Using KeyMap in Editable JComboBoxes and JTable

    I am using Keymapping for JTextFields. It works fine ! I am interested in extending the keymap feature to JComboBoxes and JTable.

    if you want to do the keymapping inside the editable component of the combobox or the table, make sure you apply it on the editor component.e.g. comboBox.getEditor().getEditorComponent() and table.getCellEditor().getTableCellEditorComponent().

  • Multicolumn JCombobox As a JTable Cell Editor

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

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

  • Directly enter edit mode of JTable cell

    Hi Everyone,
    On my UI, i am showing editable JTable. When I click on table's row / cell, it selects the row. Fine.
    But I want that it should directly enter edit mode of cell and the whole text is to be selected and highlighted and focussed.
    Thus, user can directly type the new text.
    Please suggest correct approach to handle this scenario.
    Thanks in advance.
    Girish Varde.

    Here is my attempt at solving this problem:
    **  For text selection you have two choices. Remove the "xxx" from either
    **  editCellAt() or prepareEditor() method.
    **  The difference is in how mouse double clicking works
    **  To place a cell directly into edit mode, use the changeSelection() method.
    **  Be aware this will generate a TableModelEvent every time you leave a cell.
    **  You can also use either of the above text selection methods.
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    public class TableEditCell extends JFrame
         public TableEditCell()
              String[] columnNames = {"Number", "Letter"};
              Object[][] data = { {"1", "A"}, {"2", "B"}, {"3", "C"} };
              JTable table = new JTable(data, columnNames)
                   //  Place cell in edit mode when it 'gains focus'
                   public void xxxchangeSelection(
                        int row, int column, boolean toggle, boolean extend)
                        super.changeSelection(row, column, toggle, extend);
                        if (editCellAt(row, column))
                             getEditorComponent().requestFocusInWindow();
                   //  Select the text when the cell starts editing
                   //  a) text will be replaced when you start typing in a cell
                   //  b) text will be selected when you use F2 to start editing
                   //  c) text will be selected when double clicking to start editing
                   public boolean xxxeditCellAt(int row, int column, EventObject e)
                        boolean result = super.editCellAt(row, column, e);
                        final Component editor = getEditorComponent();
                        if (editor != null && editor instanceof JTextComponent)
                             if (e == null)
                                  ((JTextComponent)editor).selectAll();
                             else
                                  SwingUtilities.invokeLater(new Runnable()
                                       public void run()
                                            ((JTextComponent)editor).selectAll();
                        return result;
                   //  Select the text when the cell starts editing
                   //  a) text will be replaced when you start typing in a cell
                   //  b) text will be selected when you use F2 to start editing
                   //  c) caret is placed at end of text when double clicking to start editing
                   public Component xxxprepareEditor(
                        TableCellEditor editor, int row, int column)
                        Component c = super.prepareEditor(editor, row, column);
                        if (c instanceof JTextComponent)
                             ((JTextField)c).selectAll();
                        return c;
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              TableEditCell frame = new TableEditCell();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • How to use Jtable cell Editor

    HI,
    Here trying to populate the ImageIcon using JLabel in Jtable cell. For that I used DefaultCellRenderer. For implement the mouseListener to label I used the DefaultCellEditor. I am facing one problem here. After editing the label I selected the second row of the table, the first row image is not displaying. Can any one help on this issue?
    public class LabelCellEditor extends DefaultCellEditor {
    public LabelCellEditor(final JCheckBox checkBox) {
    super(checkBox);
    public Component getTableCellEditorComponent(final JTable table, final Object value,
    final boolean isSelected, final int row, final int column) {
    Color background = null;
    background = ColorManager.SELECTED_ROW_BGCOLOR;
    labelVal = (JLabel) value;
    labelVal.setOpaque(true);
    labelVal.setFont(FontManager.TABLE_DATA_FONT);
    labelVal.setBackground(background);
    labelPanel = new JPanel();
    labelPanel.setOpaque(true);
    labelPanel.setBackground(background);
    labelPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
    labelPanel.setBorder(new EmptyBorder(5, 0, 0, 0));
    labelPanel.add(labelVal);
    return this.labelPanel;
    public Object getCellEditorValue() {
    return this.labelPanel;
    public class LabelCellRenderer extends DefaultTableCellRenderer {
    public LabelCellRenderer(final int alignment) {
    //setHorizontalAlignment(alignment);
    this.align = alignment;
    public Component getTableCellRendererComponent(final JTable table, final Object value,
    final boolean isSelected, final boolean hasFocus, final int row, final int column) {
    if (value != null) {
    if (value instanceof JLabel) {
    labelVal = (JLabel) value;
    labelVal.setOpaque(true);
    labelVal.setFont(FontManager.TABLE_DATA_FONT);
    labelVal.setBackground(background);
    labelVal.setHorizontalAlignment(this.align);
    labelVal.setBorder(new EmptyBorder(0, LRPADD, 0, LRPADD));
    JPanel panel = new JPanel();
    panel.setOpaque(true);
    panel.setBackground(background);
    panel.setLayout(new FlowLayout(FlowLayout.LEFT));
    panel.setBorder(new EmptyBorder(5, 0, 0, 0));
    panel.add(labelVal);
    return panel;
    return this;
    }

    With more than 30 postings you should know by now how to use the "Code" tags when posting code so the code reatains its original formatting and is therefore more readable.
    There is no need to create a custom editor, here is a simple example.

  • Help!!! JTable cell editor problem...

    I am having a problem with table cell editors.
    The problem is that when I click on another component
    in the frame (out side of the JTable) the cell editors's
    stopCellEditing() is not called so I get a JTable with a cell
    editor in editing mode.
    Any help?
    Thanks a lot

    It is difficult to tell what happens with FocusEvents when you are actually editing a cell and the editor is "up". I am experiencing different difficulties with the same root issue. I think the problem here is that the Java Focus Manager is consuming the focus event without propagating the event to any of the JTable components (CellEditor or JTable). I am not sure if this is exactly the case but I haven't been able to trap focus events in the Editors, Renderers or JTable anywhere. If the editor is not "up" then event handling seems to be fairly normal but when you are actually editing a cell it becomes tricky.
    However, this is a problem I fixed by placing a FocusGained event handler on the other (non JTable) component and then manually stopping editing on the JTable. In other words in the JFrame (or whatever component you are using) I added a FocusListener to the non JTable component and inside of FocusGanied() I execute:
    public void focusGained(FocusEvent e){
    table.getCellEditor().stopEditing();
    table.removeEditor();
    You could, of course, use cancelEditing() as well. You'll probably want to wrap the code with some robustness as follows to ensure that you don't get trapped by wierdness.
    public void focusGained(FocusEvent e){
    if (table.isEditing() && table.getCellEditor() != null){
    table.getCellEditor().stopEditing();
    table.removeEditor();
    This is probably not the only way to solve the problem but it was the way that worked when I encountered that issue.

  • JTable Cell Editor Problems

    Hi All,
    I have a problem concerning the editing for my table. When I click on a column a dialog box opens up and the user picks the values he wants. But after he presses ok in the dialog box the user again has to press enter in the selected cell or click on another cell in the table for the selected cell to lose focus.I am using a textfield as the returning component in the getcomponent method for the the table cell editor. Is there a way I can force the textfield to register an enter automatically so it loses focus or is there another way?
    Thanks, in advance.

    this is how my code is structured:
    public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor,
         ActionListener{
         private static final long serialVersionUID = 0;
         private int clickCountToStart = 2; // Default value is double click
         private JFrame editingFrame;
         // This is the component that will handle the editing of the cell value
         JTextField txtresult = new JTextField(10);
         String result = null;
         public MyTableCellEditor(JFrame jframe){
              //txtresult.addActionListener(this);       
              editingFrame = jframe;
        public int getClickCountToStart(){
            return clickCountToStart;
        public int setClickCountToStart(int c){
            clickCountToStart = c;
             return clickCountToStart;
        public boolean isCellEditable(EventObject e){
            if(e instanceof MouseEvent){
                 if(((MouseEvent)e).getClickCount()>=this.getClickCountToStart()){
                      return true;
            return false;
        public boolean stopCellEditing(){
             fireEditingStopped();
             return true;
        // This method is called when a cell value is edited by the user.
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int col) {
             // Make certain columns non editable
             if(table.getColumnName(col).equals("Sub Number")){
                  return null;
             else if(table.getColumnName(col).equals("Transmitter#/Receiver#")){
                  return null;
             if(table.getColumnName(col).equals("TOOLMODE")){
                  result = toolModeModify();
                 if(result==null){
                      result = value.toString();
                  if(result != null){
                      txtresult.setText(result);
                 else{
                      txtresult.setText(value.toString());
            else{
                 result = ModifyCell();
                 if(result != null){
                      txtresult.setText(result);
                 else{
                      if(value != null){
                           txtresult.setText(value.toString());
             txtresult.setEditable(false);
             return txtresult;
        public void actionPerformed(ActionEvent e) {
            //stopCellEditing(); //Make the renderer reappear.
        // This method is called when editing is completed.
        // It must return the new value to be stored in the cell.
        public Object getCellEditorValue() {
             try{
                 return txtresult.getText();
             }catch(NullPointerException ne){
                  return null;
        private String toolModeModify(){
             Object[] possibilities = {"0", "1", "2","3"};
             String number = (String)JOptionPane.showInputDialog(
                                 editingFrame,
                                 "Option 0: Receiver\n"
                                 + "Option 1: UDT\n"
                                 + "Option 2: TRX/UDR\n" +
                                 "Option 3: OFF\n",
                                 "Select Mode",
                                 JOptionPane.PLAIN_MESSAGE,
                                 null,
                                 possibilities,
                                 "0");
             return number;
        private String ModifyCell(){
              String editCell = "Edit Cell Value";
              String s;
              s = JOptionPane.showInputDialog(editingFrame, editCell, null,
                        JOptionPane.PLAIN_MESSAGE);
              if(s != null){
                   return s;
              else{
                   return null;
    }I dont know what I am doing wrong.

  • JTable cell editor problem

    Hi, I have a custom cell editor component being used on my JTable (a calendar component) and am having problems bringing the component out of edit mode when selecting another cell.
    If I click on a cell it enters edit mode correctly, the I can drop a popup window out from this editor to display the calendar. If however I move to another cell this window remains active.
    Could anyone explain how to come out of edit mode when moving to another cell (not necessarily selecting just moving the mouse in to another) ?
    I also have a second problem in that the calendar editor doesn't set the value in to the cell when choosing a date from the component. It keeps the original value that was in the cell. I have implemented a setValueAt() method so I'm not sure why this is not fired, any ideas?? Code is below :
    public class DueDateTableModel extends AbstractTableModel {
        private Vector vAllDueDates = null;
        private Connection conn = null;
        private Statement stmt = null;
        private ResultSet rsDueDates = null;
        private int iColCount;
        private String sSqlDueDates = null;
        private String[] testColNames = null;
        public DueDateTableModel(int pColCount, Vector pAllDueDates, String[] pColNames){
            iColCount = pColCount;
            vAllDueDates = pAllDueDates;
            testColNames = pColNames;
            populateTableCells();
            //setupEditors();
        public int getColumnCount() {
            return iColCount;
        public int getRowCount() {
            return vAllDueDates.size();
        public String getColumnName(int iCol) {
              return testColNames[iCol];
        public Object getValueAt(int iRow, int iCol) {
            // TODO Auto-generated method stub
            Vector v = (Vector)vAllDueDates.elementAt(iRow);
            return v.elementAt(iCol);
        public void setValueAt(Object oValue, int iRow, int iCol) {
            Vector v = (Vector)vAllDueDates.elementAt(iRow);
            v.setElementAt(oValue,iCol);
            fireTableCellUpdated(iRow,iCol);
        public boolean isCellEditable(int iRow, int iCol) {
            if(getValueAt(iRow,iCol)==null){
                return false;
            }else{
                return true;
        private class DueDateEditor extends CalendarComboBox implements TableCellEditor{
            //protected EventListenerList listenerList = new EventListenerList();
            //protected ChangeEvent changeEvent = new ChangeEvent(this);
            public DueDateEditor(){
                super();
            public void removeCellEditorListener(CellEditorListener l){
                //listenerList.remove(CellEditorListener.class, l);
            public Component getTableCellEditorComponent(JTable table, Object value
                    , boolean isSelected, int row, int column){
                //Just return the input panel and not the panel that the calendar comboBox is on
                return this.inputPanel;
              public Object getCellEditorValue(){
                  return this.getDate();
              public boolean isCellEditable(EventObject evt) {
                //if (evt instanceof MouseEvent) {
                  //  return ((MouseEvent)evt).getClickCount() >= 2;
                return true;
              public boolean shouldSelectCell(EventObject anEvent){
                  return false;
              public boolean stopCellEditing(){
                  //this.setDate();
                  return true;
              public void cancelCellEditing(){
              public void addCellEditorListener(CellEditorListener l){
                  //listenerList.add(CellEditorListener.class, l);
              /*protected void fireEditingStopped() {
                  CellEditorListener listener;
                  Object[] listeners = listenerList.getListenerList();
                   for (int i = 0; i < listeners.length; i++) {
                         if (listeners[i] == CellEditorListener.class) {
                                listener = (CellEditorListener) listeners[i + 1];
                                listener.editingStopped(changeEvent);
        }Sorry the classes are quite basic, I'm not very familiar with custom cell editors, I have normally used default ones like combobox etc.
    Regards
    Alan

    To get better help sooner, post a SSCCE that clearly demonstrates your problem.
    To post code, use the code tags -- [code]Your Code[/code]will display asYour CodeOr use the code button above the editing area and paste your code between the {code}{code} tags it generates.
    luck, db

  • How come I cannot use the Editing tools when i am using Adobe Acrobat Reader DC It wants me to Buy Now.  But when I use Adobe Acrobat Pro DC i have no problem using the Editing tool yet   I had Adoboe Acrobat XI Pro then it was upgraded to this DC stuff

    I am already paying a subscription for Adobe Acrobat XI Pro  Now it want me to buy when using the edit tool or even the tool to insert pages Never had that problem before??????????????

    Acrobat Reader can't edit PDF files. Use Adobe Acrobat Pro DC.

Maybe you are looking for

  • Creation of new domains in weblogic

    Hi All, I need to create two new domain in weblogic. It should be start & stop from the admin console. How to do that. What is node manager? Just assigning the managed server with machine will do the start and stop from admin console. ?

  • How can i set up an apple id to download apps without a credit card?

    I have several Ipads in school to set up for apps, but we don't have a school credit card and only want to use iTune cards. How can I set up an multiply id without using credit card details?

  • Pls help!  update 06-28-2006 erased my library!

    I was given the option to upload my the latest version of ipod and i selected 'update' and then when i went to open my library, it was all erased! i am devastated and hope it isn't gone forever . . . anyone have any advice??

  • Conversion function module

    Hello Friends,           When ever i down load into excel file the filed 'WERKS' is becoming from '0780' to 780 and when i try to upload i am getting as 780 which is creating  some problems. Is there any conversion function module to convert the the

  • Error in TDS

    Dear Experts                   In TDS form 16A i created particular vendor  AP invoice along with withholding Tax and also i defined the TDS setup in form 16A  if i give the generate the  certificate no ..............................error is showing