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.

Similar Messages

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

  • 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

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

  • Adding JComboBox in JTable?

    Hi,
    How can i add a JComboBox inside the cell of a JTable. sothat i can select options from the cell of JTable.?
    or any other idea for that?
    Thank you ;
    Ganesh.

    Swing related questions should be posted in the Swing forum.
    "Using a Combo Box as an Editor"
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#combobox

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

  • Not Updating the Values in the JComboBox and JTable

    Hi Friends
    In my program i hava Two JComboBox and One JTable. I Update the ComboBox with different field on A Table. and then Display a list of record in the JTable.
    It is Displaying the Values in the Begining But when i try to Select the Next Item in the ComboBox it is not Updating the Records Eeither to JComboBox or JTable.
    MY CODE is this
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.DefaultComboBoxModel.*;
    import javax.swing.table.*;
    import java.sql.*;
    import java.util.*;
    public class SearchBook extends JDialog implements ActionListener
         private JComboBox comboCategory,comboAuthor;
         private JSplitPane splitpane;
         private JTable table;
         private JToolBar toolBar;
         private JButton btnclose, btncancel;
         private JPanel panel1,panel2,panel3,panel4;
         private JLabel lblCategory,lblAuthor;
         private Container c;
         //DefaultTableModel model;
         Statement st;
         ResultSet rs;
         Vector v = new Vector();
         public SearchBook (Connection con)
              // Property for JDialog
              setTitle("Search Books");
              setLocation(40,110);
              setModal(true);
              setSize(750,450);
              // Creating ToolBar Button
              btnclose = new JButton(new ImageIcon("Images/export.gif"));
              btnclose.addActionListener(this);
              // Creating Tool Bar
              toolBar = new JToolBar();
              toolBar.add(btnclose);
              try
                   st=con.createStatement();
                   rs =st.executeQuery("SELECT BCat from Books Group By Books.BCat");
                   while(rs.next())
                        v.add(rs.getString(1));
              catch(SQLException ex)
                   System.out.println("Error");
              panel1= new JPanel();
              panel1.setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.HORIZONTAL;
              lblCategory = new JLabel("Category:");
              lblCategory.setHorizontalAlignment (JTextField.CENTER);
              c.gridx=2;
              c.gridy=2;
              panel1.add(lblCategory,c);
              comboCategory = new JComboBox(v);
              comboCategory.addActionListener(this);
              c.ipadx=20;
              c.gridx=3;
              c.gridwidth=1;
              c.gridy=2;
              panel1.add(comboCategory,c);
              lblAuthor = new JLabel("Author/Publisher:");
              c.gridwidth=2;
              c.gridx=1;
              c.gridy=4;
              panel1.add(lblAuthor,c);
              lblAuthor.setHorizontalAlignment (JTextField.LEFT);
              comboAuthor = new JComboBox();
              comboAuthor.addActionListener(this);
              c.insets= new Insets(20,0,0,0);
              c.ipadx=20;
              c.gridx=3;
              c.gridy=4;
              panel1.add(comboAuthor,c);
              comboAuthor.setBounds (125, 165, 175, 25);
              table = new JTable();
              JScrollPane scrollpane = new JScrollPane(table);
              //panel2 = new JPanel();
              //panel2.add(scrollpane);
              splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,panel1,scrollpane);
              splitpane.setDividerSize(15);
              splitpane.setDividerLocation(190);
              getContentPane().add(toolBar,BorderLayout.NORTH);
              getContentPane().add(splitpane);
         public void actionPerformed(ActionEvent ae)
              Object obj= ae.getSource();
              if(obj==comboCategory)
                   String selecteditem = (String)comboCategory.getSelectedItem();
                   displayAuthor(selecteditem);
                   System.out.println("Selected Item"+selecteditem);
              else if(obj==btnclose)
                   setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
              else if(obj==comboAuthor)
                   String selecteditem1 = (String)comboAuthor.getSelectedItem();
                   displayavailablity(selecteditem1);
                   //System.out.println("Selected Item"+selecteditem1);
                   System.out.println("Selected Author"+selecteditem1);
         private void displayAuthor(String selecteditem)
              try
              {     Vector data = new Vector();
                   rs= st.executeQuery("SELECT BAuthorandPublisher FROM Books where BCat='" + selecteditem + "' Group By Books.BAuthorandPublisher");
                   System.out.println("Executing");
                   while(rs.next())
                        data.add(rs.getString(1));
                   //((DefaultComboBoxModel)comboAuthor.getModel()).setVectorData(data);
                   comboAuthor.setModel(new DefaultComboBoxModel(data));
              catch(SQLException ex)
                   System.out.println("ERROR");
         private void displayavailablity(String selecteditem1)
                   try
                        Vector columnNames = new Vector();
                        Vector data1 = new Vector();
                        rs= st.executeQuery("SELECT * FROM Books where BAuthorandPublisher='" + selecteditem1 +"'");     
                        ResultSetMetaData md= rs.getMetaData();
                        int columns =md.getColumnCount();
                        String booktblheading[]={"Book ID","Book NAME","BOOK AUTHOR/PUBLISHER","REFRENCE","CATEGORY"};
                        for(int i=1; i<= booktblheading.length;i++)
                             columnNames.addElement(booktblheading[i-1]);
                        while(rs.next())
                             Vector row = new Vector(columns);
                             for(int i=1;i<=columns;i++)
                                  row.addElement(rs.getObject(i));
                             data1.addElement(row);
                             //System.out.println("data is:"+data);
                        ((DefaultTableModel)table.getModel()).setDataVector(data1,columnNames);
                        //DefaultTableModel model = new DefaultTableModel(data1,columnNames);
                        //table.setModel(model);
                        rs.close();
                        st.close();
                   catch(SQLException ex)
    }Please check my code and give me some Better Solution
    Thank you

    You already have a posting on this topic:
    http://forum.java.sun.com/thread.jspa?threadID=5143235

  • How to put JComboBox in JTable?

    I'm trying to put JComboBox in JTable, the following is my table model. The problem is that it doesn't display a JComboBox but a string of it, something like "MyTableModel$JComboBox....". Any help would be appreciated.
    class MyModel extends AbstractTableModel {
    String[] columnNames = {"Column One", "Column One"};
    String[] boxItem = {"Item One", "Item Two"};
    String[] rows = {"Row One", "Row Two"};
    JComboBox[] boxes = {
    new JComboBox(boxItem),
    new JComboBox(boxItem)
    Object[][] data = new Object[][]{rows, boxes};
    public Object getValueAt(int row, int col) {
    return data[col][row];
    }

    Hi,
    the TableModel is the wrong place to put the combo box. A model is just a representation for the data displayed in the table.
    A combo box, on the other hand, is a certain way for the user to edit the values in the table (and in the model). To change the way a user edits in a table you have to set the TableCellEditor. You can do this for the whole table or for a certain column.
    // in the JTable's constructor or init method
    // to set JComboBox in 2nd column
    // get 2nd column
    TableColumn column = myTable.getColumnModel().getColumn(1);
    // create combo box
    JComboBox combo = new JComboBox();
    combo.add("ItemOne");
    combo.add("ItemTwo");
    // set as editor for the column
    DefaultCellEditor editor = new DefaultCellEditor(combo);
    column.setCellEditor(editor);This is just an example. Try it w/ a simple table.

  • JList inside JTable

    Hi,
    I have a custom JList Renderer/Editor inside a JTable. Both the renderer and editor seem to be working fine, but if the List contains more data than will fit in the table cell, you can't see the rest of the data. I have a separate class for the renderer and the editor (both of which extend JList) and I have tried using the setAutoscrolls method and creating a JScrollPane in the constructor, neither of which seems to work. How can I put a scrollable JList as a cell in a JTable?

    Hi jhooie,
    Will you please send me the working codes for creating the JList inside JTable. I am in urgent need of the help.
    My email id is [email protected]
    Thank you,
    satheesh kumar

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

  • Placing JComboBox in JTable ColumnHeader

    Can any one help me on how to place a JComboBox in JTable ColumnHeader....?

    try this:
    package ComponentDisplayer;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    class JComponentCellRenderer implements TableCellRenderer
        public Component getTableCellRendererComponent(JTable table, Object value,
              boolean isSelected, boolean hasFocus, int row, int column) {
            return (JComponent)value;
    }and
    package ComponentDisplayer;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Pable
         public static void main(String[] args)
              JFrame frame = new JFrame("Table");
              frame.addWindowListener( new WindowAdapter() {
                   public void windowClosing(WindowEvent e)
                        Window win = e.getWindow();
                        win.setVisible(false);
                        win.dispose();
                        System.exit(0);
              JTable table = new JTable(3,2);
                 TableCellRenderer renderer = new JComponentCellRenderer();
                  TableColumnModel columnModel = table.getColumnModel();
                  TableColumn column0 = columnModel.getColumn(0);
                  TableColumn column1 = columnModel.getColumn(1);
                  column0.setHeaderRenderer(renderer);
                  JComboBox jb=new JComboBox();
                  jb.insertItemAt("well", 0);
                  jb.insertItemAt("done", 1);
                  column0.setHeaderValue(jb);
                  column1.setHeaderRenderer(renderer);
                  column1.setHeaderValue(new JComboBox());
              table.setAutoResizeMode(table.AUTO_RESIZE_ALL_COLUMNS);
              table.setSize(900, 1200);
              JScrollPane sp = new JScrollPane(table);
              table.setColumnSelectionAllowed(false);
             table.setRowSelectionAllowed(true);
              frame.getContentPane().add( sp );
              frame.pack();
              frame.setVisible(true);
              //frame.show();
    }as you can see adding it is not that hard but you cannot interact with them because if my memory serves well, tableheaders cannot have focus by default. So you gotta write your own implementation of header (may be using sth like: )public class MyTableHeaderRenderer extends JComponent implements
              TableCellRenderer {
         public MyTableHeaderRenderer() {
              // TODO Auto-generated constructor stub
         public Component getTableCellRendererComponent(JTable arg0, Object arg1,
                   boolean arg2, boolean arg3, int arg4, int arg5) {
              // TODO Auto-generated method stub
              return (JComponent)arg1;
         }and then use this as default renderer in your implementation.)
    E,ther you have to handle setfocus thing or keep track of mouse events
    I hope this helps

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

  • Update JTable when an item is selected in a JComboBox inside the same JTabl

    I created a JTable with a lookup JComboBox. I want to update values from the table when an item is selected in the ComboBox.
    I tried all the events posible in JComboBox, but I can not fire to update the JTable.
    Please if you have a how-to, (source) will help. Thanks.
    Regards,
    -Rory

    I tried that. But it only fires when the JComboxBox, lost the focus. And not in the "itemChange" event. How to do it width that event?
    I want something like "intemChange" event, to fire the JTable.fireTableChangeUpdate(); ... I send the code.
    * @author rory
    public class PeriodenDauerGrid extends JPortSimTable implements Serializable, ActionListener {
         * generated id
        private static final long serialVersionUID = -5270969898251578932L;
        public PeriodenDauerGrid() {
            super();
        @Override
        protected void initComponent() {
            super.initComponent();
            setModel(new PeriodenDauerGridTableModel());
            setDefaultEditor(String.class, new PeriodenCellEditor(this));
            setDefaultRenderer(String.class, new PeriodenCellRenderer());
        public void actionPerformed(ActionEvent e) {
            // HERE should fire the table update.
            // JOptionPane.showMessageDialog(null, "HOLITA!");
            PeriodenDauerGridTableModel model = (PeriodenDauerGridTableModel) getModel();
            model.fireTableDataChanged();
            updateUI();
    class PeriodenCellRenderer extends JLabel implements TableCellRenderer {
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            setHorizontalTextPosition(SwingConstants.CENTER);
            setHorizontalAlignment(SwingConstants.CENTER);
            if (row == 1) {
                setOpaque(true);
                setBackground(GuiConstants.PANEL_COLOR);
            } else {
                setOpaque(false);
                setBackground(GuiConstants.CELL_EDITOR_COLOR);
            if (value instanceof Date) {
                Date n = (Date) value;
                // String.format(format, args)
                String s = String.format("%1$td.%1$tm.%1$tY", (Date) value);
                setText(s);
            } else {
                setText(value == null ? "" : value.toString());
            return this;
    class PeriodenCellEditor extends AbstractCellEditor implements TableCellEditor {
        private JComboBox combo = new JComboBox(new String[] { "7", "84", "182", "364" });
        private JTable table = null;
        public PeriodenCellEditor(PeriodenDauerGrid table) {
            combo.addActionListener(table);
            this.table = table;
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            combo.setSelectedItem(value.toString());
            return combo;
        public Object getCellEditorValue() {
            return combo.getSelectedItem();
    }

  • Displaying a JComboBox in JTable

    I have a JComboBox in a JTable. The JComboBox contains JCheckBox's.
    To enable the user to select multiple checkbox items in the combobox, my class which extends JComboBox also implements ComboBoxEditor. In getItem I use showPopup inside a thread to enable multiple selections.
    public Object getItem()
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    showPopup();
    return getSelectedItem();
    The code that I have written works when the combobox is dsplayed in a panel. However, when it is placed in a JTable it fails with a:
    Exception occurred during event dispatching:
    java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
         at java.awt.Component.getLocationOnScreen_NoTreeLock(Component.java:1507)
         at java.awt.Component.getLocationOnScreen(Component.java:1481)
         at javax.swing.JPopupMenu.show(JPopupMenu.java:921)
         at javax.swing.plaf.basic.BasicComboPopup.show(BasicComboPopup.java:177)
         at javax.swing.plaf.basic.BasicComboBoxUI.setPopupVisible(BasicComboBoxUI.java:927)
         at javax.swing.JComboBox.setPopupVisible(JComboBox.java:790)
         at javax.swing.JComboBox.showPopup(JComboBox.java:775)
         at com.clarologic.pm.backoffice.usermanagement.accounts.usertabs.branchdetails.rolecombobox.RoleComboBox$1.run(RoleComboBox.java:155)
    The last line corresponds to the showPopup(); in the getItem() function.
    Anyone seen this and resolved it before ??
    Chris

    ICE,
    public Object getItem()
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    if (isShowing())
    showPopup();
    return getSelectedItem();
    This certainly stops the exception, however, it also wrecks the desired functionality.
    I wonder if the table renderer is getting in the way, which is causing the problem to occur.
    Chris

Maybe you are looking for