Editable JComboBox inside JTable clipping issues

Here is an example of what I am talking about
http://img95.imageshack.us/img95/9514/clipping4fw.png
As you can see, the bottom of the editable JComboBox is being clipped. Is there any way to remove what looks like the invisible border there?
Thanks
Daniel

I am not sure if I understand your question exactly. Your table's row height is not high enough so you may need to add a line of code like:
        table.setRowHeight(table.getRowHeight() + 4);to solve your problem.

Similar Messages

  • Editable JComboBox in JTable focus issue

    Please look at the sample code below.
    I am using a JComboBox as the editor for a column in the table. When a cell in that column is edited and the user presses enter, the cell is no longer in edit mode. However, the focus is now set on the next component in the scrollpane (which is a textfield).
    If I don't add the textfield and the the table is the only component in the scroll pane, then focus correctly remains on the selected cell.
    When the user exits edit mode, I'd like the table to have focus and for the cell to remain selected. How can I achieve this?
    thanks,
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import javax.swing.plaf.basic.*;
    import java.awt.Component;
    import javax.swing.JComboBox;
    import java.util.EventObject;
    import java.awt.event.*;
    import javax.swing.event.*;
    public class TableComboBoxTest extends JFrame {
         protected JTable table;
         public TableComboBoxTest() {
              Container pane = getContentPane();
              pane.setLayout(new BorderLayout());
              MyTableModel model = new MyTableModel();
              table = new JTable(model);
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              table.setSurrendersFocusOnKeystroke(true);
              TableColumnModel tcm = table.getColumnModel();
              TableColumn tc = tcm.getColumn(MyTableModel.GENDER);
              tc.setCellEditor(new MyGenderEditor(new JComboBox()));
              tc.setCellRenderer(new MyGenderRenderer());
              JScrollPane jsp = new JScrollPane(table);
              pane.add(jsp, BorderLayout.CENTER);          
              pane.add(new JTextField("focus goes here"), BorderLayout.SOUTH);
         public static void main(String[] args) {
              TableComboBoxTest frame = new TableComboBoxTest();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(500, 300);
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
         public class MyTableModel extends AbstractTableModel {
              public final static int FIRST_NAME = 0;
              public final static int LAST_NAME = 1;
              public final static int DATE_OF_BIRTH = 2;
              public final static int ACCOUNT_BALANCE = 3;
              public final static int GENDER = 4;
              public final static boolean GENDER_MALE = true;
              public final static boolean GENDER_FEMALE = false;
              public final String[] columnNames = {
                   "First Name", "Last Name", "Date of Birth", "Account Balance", "Gender"
              public Object[][] values = {
                        "Clay", "Ashworth",
                        new GregorianCalendar(1962, Calendar.FEBRUARY, 20).getTime(),
                        new Float(12345.67), "three"
                        "Jacob", "Ashworth",
                        new GregorianCalendar(1987, Calendar.JANUARY, 6).getTime(),
                        new Float(23456.78), "three1"
                        "Jordan", "Ashworth",
                        new GregorianCalendar(1989, Calendar.AUGUST, 31).getTime(),
                        new Float(34567.89), "three2"
                        "Evelyn", "Kirk",
                        new GregorianCalendar(1945, Calendar.JANUARY, 16).getTime(),
                        new Float(-456.70), "One"
                        "Belle", "Spyres",
                        new GregorianCalendar(1907, Calendar.AUGUST, 2).getTime(),
                        new Float(567.00), "two"
              public int getRowCount() {
                   return values.length;
              public int getColumnCount() {
                   return values[0].length;
              public Object getValueAt(int row, int column) {
                   return values[row][column];
              public void setValueAt(Object aValue, int r, int c) {
                   values[r][c] = aValue;
              public String getColumnName(int column) {
                   return columnNames[column];
              public boolean isCellEditable(int r, int c) {
                   return c == GENDER;
         public class MyComboUI extends BasicComboBoxUI {
              public JList getList()
                   return listBox;
         public class MyGenderRenderer extends DefaultTableCellRenderer{
              public MyGenderRenderer() {
                   super();
              public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                        boolean hasFocus, int row, int column) {
                   JComboBox box = new JComboBox();
                   box.addItem(value);
                   return box;
         public class MyGenderEditor extends DefaultCellEditor  { // implements CaretListener {
              protected EventListenerList listenerList = new EventListenerList();
              protected ChangeEvent changeEvent = new ChangeEvent(this);
              private JTextField comboBoxEditorTField;
              Object newValue;
              JComboBox _cbox;
              public MyGenderEditor(JComboBox cbox) {
                   super(cbox);
                   _cbox = cbox;
                   comboBoxEditorTField = (JTextField)_cbox.getEditor().getEditorComponent();
                   _cbox.addItem("three");
                   _cbox.addItem("three1");
                   _cbox.addItem("three2");
                   _cbox.addItem("One");
                   _cbox.addItem("two");
                   _cbox.setEditable(true);
                   _cbox.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
                             System.out.println("\nactionPerformed ");
                             fireEditingStopped();
              public void addCellEditorListener(CellEditorListener listener) {
                   listenerList.add(CellEditorListener.class, listener);
              public void removeCellEditorListener(CellEditorListener listener) {
                   listenerList.remove(CellEditorListener.class, listener);
              protected void fireEditingStopped() {
                   System.out.println("fireEditingStopped called ");
                   CellEditorListener listener;
                   Object[] listeners = listenerList.getListenerList();
                   for (int i = 0; i < listeners.length; i++) {
                        if (listeners[i] instanceof CellEditorListener) {
                             System.out.println("calling editingStopped on listener....................");                    
                             listener = (CellEditorListener) listeners;
                             listener.editingStopped(changeEvent);
              protected void fireEditingCanceled() {
                   System.out.println("fireEditingCanceled called ");
                   CellEditorListener listener;
                   Object[] listeners = listenerList.getListenerList();
                   for (int i = 0; i < listeners.length; i++) {
                        if (listeners[i] instanceof CellEditorListener) {
                             listener = (CellEditorListener) listeners[i];
                             listener.editingCanceled(changeEvent);
              public void cancelCellEditing() {
                   System.out.println("cancelCellEditing called ");
                   fireEditingCanceled();
              public void addNewItemToComboBox() {
                   System.out.println("\naddNewItemToComboBox called ");
                   // tc - start
                   String text = comboBoxEditorTField.getText();
                   System.out.println("text = "+text);                    
                   int index = -1;
                   for (int i = 0; i < _cbox.getItemCount(); i++)
                        String item = ((String)_cbox.getItemAt(i));
                        System.out.println("item in cbox = "+item);
                        if (item.equals(text))
                             System.out.println("selecting item now...");                              
                             index = i;
                             _cbox.setSelectedIndex(index);
                             break;
                   if (index == -1)
                        _cbox.addItem(text);
                        int count = _cbox.getItemCount();
                        _cbox.setSelectedIndex(count -1);
              public boolean stopCellEditing() {
                   System.out.println("stopCellEditing called ");
                   fireEditingStopped();
                   _cbox.transferFocus();
                   return true;
              public boolean isCellEditable(EventObject event) {
                   return true;     
              public boolean shouldSelectCell(EventObject event) {
                   return true;
              public Object getCellEditorValue() {
                   System.out.println("- getCellEditorValue called returning val: "+_cbox.getSelectedItem());
                   return _cbox.getSelectedItem();
              public Component getTableCellEditorComponent(JTable table, Object value,
                        boolean isSelected, int row, int column) {
                   System.out.println("\ngetTableCellEditorComponent "+value);
                   String text = (String)value;               
                   for (int i = 0; i < _cbox.getItemCount(); i++)
                        String item = ((String)_cbox.getItemAt(i));
                        System.out.println("item in box "+item);
                        if (item.equals(text))
                             System.out.println("selecting item now...");     
                             _cbox.setSelectedIndex(i);
                             break;
                   return _cbox;

    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,

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

    I have a jcombobox inside jtable.now i want to access its items by keys only..without using F2 key.for example if i press 's' key..the whole combobox shud popup and value 'string' is selected.please help me regarding this.

    I am not sure if I understand your question exactly. Your table's row height is not high enough so you may need to add a line of code like:
            table.setRowHeight(table.getRowHeight() + 4);to solve your problem.

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

  • 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

  • Multiple keystrokes selection for a JComboBox in JTable

    Has anyone used multiple keystrokes selection in a JComboBox inside JTable before? I can get it done outside JTable by using: http://javaalmanac.com/egs/javax.swing/combobox_CbMultiKey.html
    Looks like JTable has all kinds of problems to support JComboBox.
    Suggestions?
    Thanks,
    James

    If I read you right, you want to use a multiple keystroke combo box as an editor in a JTable?
    If you create the JComboBox as you would like it and then install it as an editor in the column(s) JTable the editor will work like the JComboBox
    Example:
    //- you would have that keyselection Manager class
    // This key selection manager will handle selections based on multiple keys.
    class MyKeySelectionManager implements JComboBox.KeySelectionManager {    ....    };
    //- Create the JComboBox with the multiple keystroke ability
    //- Create a read-only combobox
    String[] items = {"Ant", "Ape", "Bat", "Boa", "Cat", "Cow"};
    JComboBox cboBox = new JComboBox(items);
    // Install the custom key selection manager
    cboBox.setKeySelectionManager(new MyKeySelectionManager());
    //- combo box editor for the JTable
    DefaultCellEditor cboBoxCellEditor = new DefaultCellEditor(cboBox);
    //- set the editor to the specified COlumn in the JTable - for example the first column (0)
    tcm.getColumn(0).setCellEditor(cboBoxCellEditor); Finally, it may be necessary to to put a KeyPressed listener for the Tab key, and if you enter the column that has the JComboBox:
    1) start the editting
    table.editCellAt(row, col);2) get the editor component and cast it into a JComboBox (in this case)
    Component comp = table.getEditorComponent();
    JComboBox cboComp = (JComboBox) comp;3) give this compent the foucus to do its deed     
    cboComp.requestFocus();Hope this helps!
    dd

  • JTable with editable JComboBoxes

    For some reason once I added editable JComboBoxes to a JTable I can no longer tab among the fields in the table. If I just select a cell, I can tab to the other cells in that row, and then to proceeding rows as I reach the end of each. However if I double click the cell and enter data or select from the combobox. I no longer can tab to the next cell. At that point once I do hit tab, I am taken to the next table. Not the next cell in the row, or the next row in the current table.
    I have tried messing with a bunch of listeners, but I am not using the right listener on the right object? What listerner and object should the listener belong to? Table, model, cell editor, combobox, jpanel, jframe ? I hope this is not to vague.

    Well I am starting to think it's an implementation issue. Like I am not doing it how I should. I am basically doing
    JComboBox jcb = new JComboBox();
    jcb.setEditable(true);
    column.setCellEditor(new DefaultCellEditor(jcb));
    When I think I should be inheriting, and creating my own editor and/or renderer? Now my combobox vars are globally available in the class, so I can set and clear their contents. It does not matter that each row in the table has the same content in the combo boxes, that's basically what I want. User to be able to select an existing entry or make a new one.
    What I am trying to do is on tables have a drop down box that shows up when a user types a matching entry. If no entry matches, no popup box. If entry matches, box pops up and shows possible entries starting with what they are typing. Like code completion in IDE's like Netbeans. However I am doing this in a table. I thought a JComboBox would be a good widget to start with?

  • Editable JComboBox in a JTable

    I posted my problem into the "Java Essentials/Java programming" forum but it would be much better if I'd posted it here into the swing theme :).
    Here it is what I posted:
    Funky_1321
    Posts:8
    Registered: 2/22/06
    editable JComboBox in a JTable
    Oct 21, 2006 1:32 PM
    Click to email this message
    Hello!
    Yesterday I posted a problem, solved it and there's another one, referring the same theme.
    So it's about a editable JComboBox with autocomplete function. The combo is a JTables cellEditors component. So it's in a table. So when the user presses the enter key to select an item from the JComboBox drop down menu, I can't get which item is it, not even which index has the item in the list. If for exemple the JComboBox isn't in a table but is added on a JPanel, it works fine. So I want to get the selectedItem in the actionPerformed method implemented in the combo box. I always get null instead of the item.
    Oh... if user picks up some item in the JComboBox-s list with the mouse, it's working fine but I want that it could be picked up with the enter key.
    Any solutions appreciated!
    Thanks, Tilen
    YAT_Archivist
    Posts:1,321
    Registered: 13/08/05
    Re: editable JComboBox in a JTable
    Oct 21, 2006 1:55 PM (reply 1 of 2)
    Click to email this message
    I suggest that you distill your current code into a simple class which has the following attributes:
    1. It can be copied and pasted and will compile straight out.
    2. It has a main method which brings up a simple example frame.
    3. It's no more than 50 lines long.
    4. It demonstrates accurately what you've currently got working.
    Without that it's hard to know exactly what you're currently doing, and requires a significant investment of time for someone who hasn't already solved this problem before to attempt to help. I'm not saying that you won't get help if you don't post a simple demo class, but it will significantly improve your chances.
    Funky_1321
    Posts:8
    Registered: 2/22/06
    Re: editable JComboBox in a JTable
    Oct 21, 2006 2:11 PM (reply 2 of 2)
    Click to email this message
    Okay ... I'll write the code in short format:
    class acJComboBox extends JComboBox {
      public acJComboBox() {
        this.setEditable(true);
        this.setSelectedItem("");
        this.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) {
         // ... code code code
         // that's tricky ... the method getSelectedItem() always returns null - remember; the acJComboBox is in a JTable!
         if (e.getKeyCode() == 10 && new String((String)getEditor().getItem()).length() != 0) { getEditor().setItem(getSelectedItem()); }
    }And something more ... adding the acJComboBox into the JTable:
    TableColumn column = someTable.getColumn(0);
    column.setCellEditor(new DefaultCellEditor(new acJComboBox());
    So if the user presses the enter key to pick up an item in the combo box drop down menu, it should set the editors item to the selected item from the drop down menu (
    getEditor().setItem(getSelectedItem());
    When the acJComboBox is on a usual JPanel, it does fine, but if it's in the JTable, it doesn't (getSelectedItem() always returns null).
    Hope I described the problem well now ;).

    Okay look ... I couldn't write a shorter code just for an example. I thought that my problem could be understoodable just in mind. However ... type in the first combo box the letter "i" and then select some item from the list with pressing the enter key. Do the same in the 2nd combo box who's in the JTable ... the user just can't select that way if the same combo is in the JTable. Why? Thanks alot for future help!
    the code:
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.Vector;
    import javax.swing.DefaultCellEditor;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;
    class Example extends JFrame {
        private String[] columns = { "1", "2", "3" };
        private String[][] rows = {};
        private DefaultTableModel model = new DefaultTableModel(rows, columns);
        private JTable table = new JTable(model);
        private JScrollPane jsp = new JScrollPane(table);
        private acJComboBox jcb1 = new acJComboBox();
        private acJComboBox jcb2 = new acJComboBox();
        public Example() {
            // initialize JFrame
            this.setLayout(null);
            this.setLocation(150, 30);
            this.setSize(300, 300);
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
            // initialize JFrame
            // initialize components
            Vector<String> v1 = new Vector<String>();
            v1.add("item1");
            v1.add("item2");
            v1.add("item3");
            jcb1.setData(v1);
            jcb2.setData(v1);
            jcb1.setBounds(30, 30, 120, 20);
            jsp.setBounds(30, 70, 250, 100);
            add(jcb1);
            add(jsp);
            TableColumn column = table.getColumnModel().getColumn(0);
            column.setCellEditor(new DefaultCellEditor(jcb2));
            Object[] data = { "", "", "" };
            model.addRow(data);
            // initialize components
            this.setVisible(true);
        public static void main(String[] args) {
            Example comboIssue = new Example();
    class acJComboBox extends JComboBox {
        private Vector<String> data = new Vector<String>();
        private void init() {
            this.setEditable(true);
            this.setSelectedItem("");
            this.setData(this.data);
            this.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) {
                        if (e.getKeyCode() != 38 && e.getKeyCode() != 40) {
                            String a = getEditor().getItem().toString();
                            setModel(new DefaultComboBoxModel());
                            int st = 0;
                            for (int i = 0; i < getData().size(); i++) {
                                String str1 = a.toUpperCase();
                                String tmp = (String)getData().get(i).toUpperCase();
                                if (str1.length() <= tmp.length()) {
                                    String str2 = tmp.substring(0, str1.length());
                                    if (str1.equals(str2)) {
                                        DefaultComboBoxModel model = (DefaultComboBoxModel)getModel();
                                        model.insertElementAt(getData().get(i), getItemCount());
                                        st++;
                            getEditor().setItem(new String(a));
                            JTextField jtf = (JTextField)e.getSource();
                            jtf.setCaretPosition(jtf.getDocument().getLength());
                            hidePopup();
                            if (st != 0 && e.getKeyCode() != 10 && new String((String)getEditor().getItem()).length() != 0) { showPopup(); }
                            if (e.getKeyCode() == 10 && new String((String)getEditor().getItem()).length() != 0) { getSelectedItem(); }
                            if (new String((String)getEditor().getItem()).length() == 0) { whenEmpty(); }
            this.addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) {
                hidePopup();
        // - constructors -
        public acJComboBox() {
            init();
        public acJComboBox(Vector<String> data) {
            this.data = data;
            init();
        // - constructors -
        // - interface -
        public void whenEmpty() { } // implement if needed
        public void setData(Vector<String> data) {
            this.data = data;
            for (int i = 0; i < data.size(); i++) {
                this.addItem(data.get(i));
        public Vector<String> getData() {
            return this.data;
        // - interface -
    }

  • Editable text inside draggable movie clip

    I am dinamically creating textfields inside movie clips.
    Those movie clips are all dragabble (startDrag).
    The problem is that those textfields are supposed to be
    editable (input type) but once I attach startDrag to them, it's
    impossible for them to get the focus, hence they are not editable.
    I tried manually setting the focus on release, but it didn't work
    (Selection.setFocus(_root.movieclip.textfield)).
    Any help will be rrrrreally appreciated :D

    Well there does have to be some pixels in the bg clip! (Got
    to tease you just a bit, because I run into this ALL the time.)
    Some how folks don't take the method at its word.
    createEmptyMovieClip() does just that. It creates and empty movie
    clip. There are no pixels in it so there is nothing to onPress.
    Also I've got a little trick for you – you didn't ask
    for it, but it is still free. :)
    If you use the MovieClip class' method for
    createEmptyMovieClip() it will return a reference to the newly
    create clip. You can assign that reference to a variable and use it
    again and again. To my eye it makes the code easier to read and
    maintain. So your code would change to something like:
    var curClip=this.createEmptyMovieClip("mc"+i,1000+i);
    curClip.createEmptyMovieClip("bg",100);
    curClip.createTextField("myText",2,20,20,"auto","auto");
    curClip.myText.text="default value";
    curClip.bg.onPress=function(){
    this._parent.startDrag();
    and so on.
    Also I personally think getNextHighestDepth() is a disaster
    waiting to happen so I personally never use it.

  • JTextArea inside Jtable - Tab, Focus issues

    I am facing the following problems with JTextArea inside Jtable Cell
    1. blinking cursor not visible on the cell(0,0) first time the UI is shown, although it has the focus
    2. blinking cursor not visible on the 5th column (JTextArea) when it receives the focus nor the characters are visible when i start typing. i have to manually double click to force the focus to shift to the cell.
    3. focus does not shit out of the 5th column (JTextArea) after pressing the tab key or enter key once. i have to do that twice to force the focus out.
    Following is the code which i have implemented. Please let me know what is being missed out to rectify the above problems.
    Thanks.
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.BorderFactory;
    import javax.swing.DefaultCellEditor;
    import javax.swing.InputMap;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
    public class test extends JFrame {
         JTable table;
         public test() {
              table = new JTable(15, 5) {
                   public boolean isCellEditable(int row, int column) {
                        return column % 2 == 0;
                        // return true;
                   public void changeSelection(final int row, final int column,
                             boolean toggle, boolean extend) {
                        super.changeSelection(row, column, toggle, extend);
                        if (editCellAt(row, column)) {
                             getEditorComponent().requestFocusInWindow();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              TextAreaRenderer textAreaRenderer = new TextAreaRenderer();
              TextAreaEditor textEditor = new TextAreaEditor();
              table.getColumnModel().getColumn(4).setCellRenderer(textAreaRenderer);
              table.getColumnModel().getColumn(4).setCellEditor(textEditor);
              JTextField tf = new JTextField();
              tf.setBorder(BorderFactory.createEmptyBorder());
              table.setDefaultEditor(Object.class, new DefaultCellEditor((tf)));
              JScrollPane scrollPane = new JScrollPane(table);
              DefaultCellEditor dce = (DefaultCellEditor) table
                        .getDefaultEditor(Object.class);
              dce.setClickCountToStart(1);
              getContentPane().add(scrollPane);
              InputMap im = table
                        .getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
              // Have the enter key work the same as the tab key
              KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
              KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
              im.put(enter, im.get(tab));
              // Disable the right arrow key
              KeyStroke right = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
              im.put(right, "none");
              // Override the default tab behaviour
              // Tab to the next editable cell. When no editable cells goto next cell.
              final Action oldTabAction = table.getActionMap().get(im.get(tab));
              Action tabAction = new AbstractAction() {
                   public void actionPerformed(ActionEvent e) {
                        oldTabAction.actionPerformed(e);
                        JTable table = (JTable) e.getSource();
                        int rowCount = table.getRowCount();
                        int columnCount = table.getColumnCount();
                        int row = table.getSelectedRow();
                        int column = table.getSelectedColumn();
                        while (!table.isCellEditable(row, column)) {
                             column += 1;
                             if (column == columnCount) {
                                  column = 0;
                                  row += 1;
                             if (row == rowCount) {
                                  row = 0;
                             // Back to where we started, get out.
                             if (row == table.getSelectedRow()
                                       && column == table.getSelectedColumn()) {
                                  break;
                        table.changeSelection(row, column, false, false);
              table.getActionMap().put(im.get(tab), tabAction);
              table.setSurrendersFocusOnKeystroke(true);
         public static void main(String[] args) {
              test frame = new test();
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.pack();
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
    import java.awt.Component;
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    public 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;
    import java.awt.KeyboardFocusManager;
    import java.awt.event.FocusEvent;
    import java.awt.event.InputEvent;
    import java.awt.event.KeyEvent;
    import java.util.HashSet;
    import java.util.Set;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComponent;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
    public 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);
              Set forwardTraversalKeys = new HashSet();
              forwardTraversalKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));
              textArea.setFocusTraversalKeys(
                        KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
                        forwardTraversalKeys);
              Set backwardTraversalKeys = new HashSet();
              backwardTraversalKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB,
                        InputEvent.SHIFT_MASK));
              textArea.setFocusTraversalKeys(
                        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
                        backwardTraversalKeys);
              scrollPane.getVerticalScrollBar().setFocusable(false);
              scrollPane.getVerticalScrollBar().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 lostFocus() {
              stopCellEditing();
    --------------------------------------------

    I am facing the following problems with JTextArea inside Jtable Cell
    1. blinking cursor not visible on the cell(0,0) first time the UI is shown, although it has the focus
    2. blinking cursor not visible on the 5th column (JTextArea) when it receives the focus nor the characters are visible when i start typing. i have to manually double click to force the focus to shift to the cell.
    3. focus does not shit out of the 5th column (JTextArea) after pressing the tab key or enter key once. i have to do that twice to force the focus out.
    Following is the code which i have implemented. Please let me know what is being missed out to rectify the above problems.
    Thanks.
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.BorderFactory;
    import javax.swing.DefaultCellEditor;
    import javax.swing.InputMap;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
    public class test extends JFrame {
         JTable table;
         public test() {
              table = new JTable(15, 5) {
                   public boolean isCellEditable(int row, int column) {
                        return column % 2 == 0;
                        // return true;
                   public void changeSelection(final int row, final int column,
                             boolean toggle, boolean extend) {
                        super.changeSelection(row, column, toggle, extend);
                        if (editCellAt(row, column)) {
                             getEditorComponent().requestFocusInWindow();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              TextAreaRenderer textAreaRenderer = new TextAreaRenderer();
              TextAreaEditor textEditor = new TextAreaEditor();
              table.getColumnModel().getColumn(4).setCellRenderer(textAreaRenderer);
              table.getColumnModel().getColumn(4).setCellEditor(textEditor);
              JTextField tf = new JTextField();
              tf.setBorder(BorderFactory.createEmptyBorder());
              table.setDefaultEditor(Object.class, new DefaultCellEditor((tf)));
              JScrollPane scrollPane = new JScrollPane(table);
              DefaultCellEditor dce = (DefaultCellEditor) table
                        .getDefaultEditor(Object.class);
              dce.setClickCountToStart(1);
              getContentPane().add(scrollPane);
              InputMap im = table
                        .getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
              // Have the enter key work the same as the tab key
              KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
              KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
              im.put(enter, im.get(tab));
              // Disable the right arrow key
              KeyStroke right = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
              im.put(right, "none");
              // Override the default tab behaviour
              // Tab to the next editable cell. When no editable cells goto next cell.
              final Action oldTabAction = table.getActionMap().get(im.get(tab));
              Action tabAction = new AbstractAction() {
                   public void actionPerformed(ActionEvent e) {
                        oldTabAction.actionPerformed(e);
                        JTable table = (JTable) e.getSource();
                        int rowCount = table.getRowCount();
                        int columnCount = table.getColumnCount();
                        int row = table.getSelectedRow();
                        int column = table.getSelectedColumn();
                        while (!table.isCellEditable(row, column)) {
                             column += 1;
                             if (column == columnCount) {
                                  column = 0;
                                  row += 1;
                             if (row == rowCount) {
                                  row = 0;
                             // Back to where we started, get out.
                             if (row == table.getSelectedRow()
                                       && column == table.getSelectedColumn()) {
                                  break;
                        table.changeSelection(row, column, false, false);
              table.getActionMap().put(im.get(tab), tabAction);
              table.setSurrendersFocusOnKeystroke(true);
         public static void main(String[] args) {
              test frame = new test();
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.pack();
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
    import java.awt.Component;
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    public 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;
    import java.awt.KeyboardFocusManager;
    import java.awt.event.FocusEvent;
    import java.awt.event.InputEvent;
    import java.awt.event.KeyEvent;
    import java.util.HashSet;
    import java.util.Set;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComponent;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
    public 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);
              Set forwardTraversalKeys = new HashSet();
              forwardTraversalKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));
              textArea.setFocusTraversalKeys(
                        KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
                        forwardTraversalKeys);
              Set backwardTraversalKeys = new HashSet();
              backwardTraversalKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB,
                        InputEvent.SHIFT_MASK));
              textArea.setFocusTraversalKeys(
                        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
                        backwardTraversalKeys);
              scrollPane.getVerticalScrollBar().setFocusable(false);
              scrollPane.getVerticalScrollBar().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 lostFocus() {
              stopCellEditing();
    --------------------------------------------

  • Reposting - JTextArea inside Jtable - Tab, Focus issues

    Sorry for reposting this again...I didn't format the code in my previous post.
    I am facing the following problems with JTextArea inside Jtable Cell
    1. blinking cursor not visible on the cell(0,0) first time the UI is shown, although it has the focus
    2. blinking cursor not visible on the 5th column (JTextArea) when it receives the focus nor the characters are visible when i start typing. i have to manually double click to force the focus to shift to the cell.
    3. focus does not shit out of the 5th column (JTextArea) after pressing the tab key or enter key once. i have to do that twice to force the focus out.
    Following is the code which i have implemented. Please let me know what is being missed out to rectify the above problems.
    Thanks.
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.BorderFactory;
    import javax.swing.DefaultCellEditor;
    import javax.swing.InputMap;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
    public class test extends JFrame {
         JTable table;
         public test() {
              table = new JTable(15, 5) {
                   public boolean isCellEditable(int row, int column) {
                        return column % 2 == 0;
                        // return true;
                   public void changeSelection(final int row, final int column,
                             boolean toggle, boolean extend) {
                        super.changeSelection(row, column, toggle, extend);
                        if (editCellAt(row, column)) {
                             getEditorComponent().requestFocusInWindow();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              TextAreaRenderer textAreaRenderer = new TextAreaRenderer();
              TextAreaEditor textEditor = new TextAreaEditor();
              table.getColumnModel().getColumn(4).setCellRenderer(textAreaRenderer);
              table.getColumnModel().getColumn(4).setCellEditor(textEditor);
              JTextField tf = new JTextField();
              tf.setBorder(BorderFactory.createEmptyBorder());
              table.setDefaultEditor(Object.class, new DefaultCellEditor((tf)));
              JScrollPane scrollPane = new JScrollPane(table);
              DefaultCellEditor dce = (DefaultCellEditor) table
                        .getDefaultEditor(Object.class);
              dce.setClickCountToStart(1);
              getContentPane().add(scrollPane);
              InputMap im = table
                        .getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
              // Have the enter key work the same as the tab key
              KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
              KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
              im.put(enter, im.get(tab));
              // Disable the right arrow key
              KeyStroke right = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
              im.put(right, "none");
              // Override the default tab behaviour
              // Tab to the next editable cell. When no editable cells goto next cell.
              final Action oldTabAction = table.getActionMap().get(im.get(tab));
              Action tabAction = new AbstractAction() {
                   public void actionPerformed(ActionEvent e) {
                        oldTabAction.actionPerformed(e);
                        JTable table = (JTable) e.getSource();
                        int rowCount = table.getRowCount();
                        int columnCount = table.getColumnCount();
                        int row = table.getSelectedRow();
                        int column = table.getSelectedColumn();
                        while (!table.isCellEditable(row, column)) {
                             column += 1;
                             if (column == columnCount) {
                                  column = 0;
                                  row += 1;
                             if (row == rowCount) {
                                  row = 0;
                             // Back to where we started, get out.
                             if (row == table.getSelectedRow()
                                       && column == table.getSelectedColumn()) {
                                  break;
                        table.changeSelection(row, column, false, false);
              table.getActionMap().put(im.get(tab), tabAction);
              table.setSurrendersFocusOnKeystroke(true);
         public static void main(String[] args) {
              test frame = new test();
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.pack();
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
    import java.awt.Component;
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    public 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;
    import java.awt.KeyboardFocusManager;
    import java.awt.event.FocusEvent;
    import java.awt.event.InputEvent;
    import java.awt.event.KeyEvent;
    import java.util.HashSet;
    import java.util.Set;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComponent;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
    public 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);
              Set forwardTraversalKeys = new HashSet();
              forwardTraversalKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));
              textArea.setFocusTraversalKeys(
                        KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
                        forwardTraversalKeys);
              Set backwardTraversalKeys = new HashSet();
              backwardTraversalKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB,
                        InputEvent.SHIFT_MASK));
              textArea.setFocusTraversalKeys(
                        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
                        backwardTraversalKeys);
              scrollPane.getVerticalScrollBar().setFocusable(false);
              scrollPane.getVerticalScrollBar().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 lostFocus() {
              stopCellEditing();
    }

    Sorry for reposting this again...I didn't format the code in my previous post.
    I am facing the following problems with JTextArea inside Jtable Cell
    1. blinking cursor not visible on the cell(0,0) first time the UI is shown, although it has the focus
    2. blinking cursor not visible on the 5th column (JTextArea) when it receives the focus nor the characters are visible when i start typing. i have to manually double click to force the focus to shift to the cell.
    3. focus does not shit out of the 5th column (JTextArea) after pressing the tab key or enter key once. i have to do that twice to force the focus out.
    Following is the code which i have implemented. Please let me know what is being missed out to rectify the above problems.
    Thanks.
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.BorderFactory;
    import javax.swing.DefaultCellEditor;
    import javax.swing.InputMap;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
    public class test extends JFrame {
         JTable table;
         public test() {
              table = new JTable(15, 5) {
                   public boolean isCellEditable(int row, int column) {
                        return column % 2 == 0;
                        // return true;
                   public void changeSelection(final int row, final int column,
                             boolean toggle, boolean extend) {
                        super.changeSelection(row, column, toggle, extend);
                        if (editCellAt(row, column)) {
                             getEditorComponent().requestFocusInWindow();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              TextAreaRenderer textAreaRenderer = new TextAreaRenderer();
              TextAreaEditor textEditor = new TextAreaEditor();
              table.getColumnModel().getColumn(4).setCellRenderer(textAreaRenderer);
              table.getColumnModel().getColumn(4).setCellEditor(textEditor);
              JTextField tf = new JTextField();
              tf.setBorder(BorderFactory.createEmptyBorder());
              table.setDefaultEditor(Object.class, new DefaultCellEditor((tf)));
              JScrollPane scrollPane = new JScrollPane(table);
              DefaultCellEditor dce = (DefaultCellEditor) table
                        .getDefaultEditor(Object.class);
              dce.setClickCountToStart(1);
              getContentPane().add(scrollPane);
              InputMap im = table
                        .getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
              // Have the enter key work the same as the tab key
              KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
              KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
              im.put(enter, im.get(tab));
              // Disable the right arrow key
              KeyStroke right = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
              im.put(right, "none");
              // Override the default tab behaviour
              // Tab to the next editable cell. When no editable cells goto next cell.
              final Action oldTabAction = table.getActionMap().get(im.get(tab));
              Action tabAction = new AbstractAction() {
                   public void actionPerformed(ActionEvent e) {
                        oldTabAction.actionPerformed(e);
                        JTable table = (JTable) e.getSource();
                        int rowCount = table.getRowCount();
                        int columnCount = table.getColumnCount();
                        int row = table.getSelectedRow();
                        int column = table.getSelectedColumn();
                        while (!table.isCellEditable(row, column)) {
                             column += 1;
                             if (column == columnCount) {
                                  column = 0;
                                  row += 1;
                             if (row == rowCount) {
                                  row = 0;
                             // Back to where we started, get out.
                             if (row == table.getSelectedRow()
                                       && column == table.getSelectedColumn()) {
                                  break;
                        table.changeSelection(row, column, false, false);
              table.getActionMap().put(im.get(tab), tabAction);
              table.setSurrendersFocusOnKeystroke(true);
         public static void main(String[] args) {
              test frame = new test();
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.pack();
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
    import java.awt.Component;
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    public 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;
    import java.awt.KeyboardFocusManager;
    import java.awt.event.FocusEvent;
    import java.awt.event.InputEvent;
    import java.awt.event.KeyEvent;
    import java.util.HashSet;
    import java.util.Set;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComponent;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
    public 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);
              Set forwardTraversalKeys = new HashSet();
              forwardTraversalKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));
              textArea.setFocusTraversalKeys(
                        KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
                        forwardTraversalKeys);
              Set backwardTraversalKeys = new HashSet();
              backwardTraversalKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB,
                        InputEvent.SHIFT_MASK));
              textArea.setFocusTraversalKeys(
                        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
                        backwardTraversalKeys);
              scrollPane.getVerticalScrollBar().setFocusable(false);
              scrollPane.getVerticalScrollBar().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 lostFocus() {
              stopCellEditing();
    }

  • Using Editor JComboBox is JTable CellEditors

    Hello all.
    I have a JTable with an editable JComboBox as a cell editor, but when it is activated the text inside the edit area is cut off.
    Example: http://www.rightstep.org/Image.jpg
    What can I do with the JComboBox settings to make more of the text visible? If some of it is cut off, that is not a huge issue -- but I'd like as much visible as possible for when people need to enter text that is not already in the drop down box.
    Thanks for any help!

    A combo box has an associated editor which in turn has an associated textfield.... get the textfield and set a null or empty border on it.
    ;o)
    V.V.

  • Combobox Autocomplete editor inside Jtable cell

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

    You need to create a custom CellEditor which will prevent these problems from occurring. The explanation behind the problem and source code for the new editor can be found at Thomas Bierhance's site http://www.orbital-computer.de/JComboBox/. The description of the problem and the workaround are at the bottom of the page.

  • How can I edit part of a clip

    How can I edit part of a clip in iMovie.

    First, select the portion of the clip that you would like to edit. Do this by dragging your mouse. A yellow border should be around this portion of the clip.
    Next, right-click inside the yellow border and select SPLIT CLIP. Now you have a separate clip that you can apply your edit to.

Maybe you are looking for

  • Updates July 5 corrupted - App Storele "Report a Problem" missing

    Apps which updated today now crash (July 5). I deleted and reinstalled, but still crash. Apple Support suggest using "Report a Problem" in the app store - it exists for iPhone, but not for iPad. I expect if I wait, the corrupt app that Apple is distr

  • Problems with the WorkItemsCube

    Hi I have some problems running the WorkItemsCube. I started the WorkItemsCube last week (15/1) and the processing failed with the error "The account is currently disabled" i found out that someone, for some reason had disabled the Analysis service a

  • Play button showing when publishing to responsive template

    I'm having difficulties when previewing and publishing a responsive project. Initially when I viewed the review/published project the first slide was blank and I had to use the TOC to navigate to the first page. I searched for a resolution and found

  • Thhink have the same problem some help

    Hello.  :D just but the MSI 694D Pro2-IR 3 week ago and still try to install....... I'm having some problems with my computer. try to install windows 2K or XP pro, start the install no problem but When it reboots the computer hangs. all the light are

  • Binary Tree: Number of Nodes at a Particular Level

    Hi, I'm trying to teach myself about binary tree but am having trouble writing an algorithm. The algorithm that I'm trying to write is one that will take a binary tree and output the number of nodes at each level of the tree (maybe in an array). I ha