Checking Unchecking of JCheckBox value  inside JTable cell

My problem is that i have jtable which has table data. In that first column has jcheckbox values which are there because of the tabledata has firstcolumn values as boolean, to know the no of checks in jcheckboxes in jtable, there is count variable which needs to be dynamic. When i first check the box the variable that i have set to know the check i.e count increases by one, then next jcheckbox if i check then count goes to 2, but real problem is when i do some 2 events on same checkbox then ie. if i check the jcheckbox , the count increases but after that the jcheckbox doesnot listen to events fired. Any help is appreciated

The example from above shows how to add Objects to a table. If you want a column of checkBoxes then simply replace the Objects in one of the columns with:
new Boolean(false)
Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html]How to Use Tables for more information.

Similar Messages

  • How to Check and Uncheck the JCheckBox in the JTable?

    Dear Friends,
    I created a Table using JTable and it consists first column is JCheckBox (JCheckBox is included in JTable by using TableCellRenderer) and two more columns with Id and Name. How to enable the check and uncheck the JCheckBox in the Table and how to get the row id or values of the rows where the CheckBox is checked?
    Thanks in Advance.
    Sathish kumar D

    Read the API for JTable and follow the link to the tutorial on how to use tables, where you will find adequate guidance and examples.
    db
    edit And isn't this post on the same topic as your previous one? If so, please add a note that responses should be posted here and not on the other thread.
    [http://forums.sun.com/thread.jspa?threadID=5353422]
    Edited by: Darryl.Burke

  • Unable to check / uncheck a checkbox in a JTable...

    Hi all,
    I know that a lot of people have asked this question before but I am unable to find a solution even after going all the messages. My issue is:
    My initial rendering of the checkboxes inside the table works ok. I am using a TableCellRenderer and my input to determine the "checked/unchecked" is string like "true" or "false" and not boolean values. But I am unable to do check / uncheck any of the checkboxes.
    I would really appreciate any pointers.
    Thanks in advance.
    Below is my code snippet:
    public Component getTableCellRendererComponent(JTable table_,
    Object value_, boolean isSelected_, boolean hasFocus_, int rowIndex_,
    int colIndex_)
    Component component = super.getTableCellRendererComponent(table_,
    value_, isSelected_, hasFocus_, rowIndex_, colIndex_);
    indicator = table_.getColumnModel().getColumnIndex("IND");      
    if (indicator == colIndex_)
         if (value_.equals("true")){
              component = new JCheckBox("", true);           
         } else {
              component = new JCheckBox("", false);           
         return component;
    }

    Your TableModel has to indicate that the column is editable. Your TableModel also has to implement setValueAt() so that when the user changes the value, it updates the data.
    The table will know to use it's own boolean renderer/editor for that column because it knows what to do when a column returns a Boolean.

  • Multiple JButtons inside JTable cell - Dispatch mouse clicks

    Hi.
    I know this subject has already some discussions on the forum, but I can't seem to find anything that solves my problem.
    In my application, every JTable cell is a JPanel, that using a GridLayout, places vertically several JPanel's witch using an Overlay layout contains a JLabel and a JButton.
    As you can see, its a fairly complex cell...
    Unfortunately, because I use several JButtons in several locations inside a JTable cell, sometimes I can't get the mouse clicks to make through.
    This is my Table custom renderer:
    public class TimeTableRenderer implements TableCellRenderer {
         Border unselectedBorder = null;
         Border selectedBorder = null;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                   boolean hasFocus, int row, int column) {
              if (value instanceof BlocoGrid) {
                   if (isSelected) {
                        if (selectedBorder == null)
                             selectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getSelectionBackground());
                        ((BlocoGrid) value).setBorder(selectedBorder);
                   } else {
                        if (unselectedBorder == null)
                             unselectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getBackground());
                        ((BlocoGrid) value).setBorder(unselectedBorder);
              return (Component) value;
    }and this is my custom editor (so clicks can get passed on):
    public class TimeTableEditor extends AbstractCellEditor implements TableCellEditor {
         private TimeTableRenderer render = null;
         public TimeTableEditor() {
              render = new TimeTableRenderer();
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int column) {
             if (value instanceof BlocoGrid) {
                  if (((BlocoGrid) value).barras.size() > 0) {
                       return render.getTableCellRendererComponent(table, value, isSelected, true, row, column);
             return null;
        public Object getCellEditorValue() {
            return null;
    }As you can see, both the renderer and editor return the same component that cames from the JTable model (all table values (components) only get instantiated once, so the same component is passed on to the renderer and editor).
    Is this the most correct way to get clicks to the cell component?
    Please check the screenshot below to see how the JButtons get placed inside the cell:
    http://img141.imageshack.us/my.php?image=calendarxo9.jpg
    If you need more info, please say so.
    Thanks.

    My mistake... It worked fine. The cell span code was malfunctioning. Thanks anyway.

  • Setting two JTextFields inside JTable cell

    hi,
    I am really stick trying to figure out how to set two cells inside a JTable cell. This needs to be done because if there is a value already inside the cell then i want to drop another value - this new value should be displayed inside another cell but along with the other value already in the cell.
    I assume that i would need to create two JTextFields.
    But can anyone help me further please.

    That should be a simple issue of customizing table cell editor and renderer.
    See tutorials.

  • Capturing events from a JCheckBox in a JTable cell

    I am trying to capture item state changed event from a JCheckbox in a JTable. When user selects checkbox I do insert in database and on deselect I do delete from database. The item state changed event is not firing correctly...can you please tell me what I am doing wrong. My JTable uses CustomModel which is used by many other apps. So I can not really modify CustomModel only to work with my JTable. Here is my code.
    public class MyClass extends JPanel
    .....some code to add panel, jscorollpane, etc.
    ResultSet res;
    GUI gui; //Custom Class to deal with different GUI layouts
    JTable myJTable = new JTable();
    GUI.CustomModel custModel;
    public void init()
         displayJTable();
    attachCheckBoxListeners();
    private void displayForms()
         res = //resultset from DB
    Vector cols = new Vector(10);
    cols.addElement(new Integer(1);
    gui.DisplayResultSetinTabel(res, myJtable, cols, null);
    custModel= (GUI.CustomModel) ((TableSorter) myJTable.getModel()).getModel();
    custModel.setEditableColumn(0, true);
    //Attach CheckBox Listener to all the checkbox in JTable
    private void attachCheckBoxListeners()
    for(int row = 0; row< myJTable.getRowCount(); row++)
    Object val = cm.getValueAt(row, 0);
    final JCheckBox jcb = (JCheckBox) gridForms.getCellEditor(row, 0).getTableCellEditorComponent(gridForms, val, true, row, 0);
    jcb.addItemListener( new java.awt.event.ItemListener() // Add Item Listener to trap events
    public void itemStateChanged(java.awt.event.ItemEvent event)
                   if(myJtable.getSelectedRow() == -1) // if no row is selected in table return
                        return;
                   try               
                   if (res.absolute(myJtable.getSelectedRow())+1))
         if(jcb.isSelected())
    saveData();();      
         else
    deleteData();
         catch(Exception e)
    System.out.println("ERROR ");
    } //end of AttachCheckBoxListeners ()
    private void SaveData() {}
    private void DeleteData() {}
    Okay....the problem is when JCheckBox state is changed (by user) from Selected to Deselected itemStateChanged() is fired and it does delete from database. then again itemStateChanged() called it detects Jcheckbox as selected and does inseret in database. On Jtable gui...that checkbox is still shown as desected.
    Please tell me what is going on here.....
    Thank you.

    In short - never listen to low-level events from editorComponents (low-level meaning everything below - and most of the time including - a editingStopped/editingCancelled of the cellEditor). Your problem belongs to the model realm - save if a cell value is changed - so solve it in the model realm by listening to event from the tableModel and trigger your business logic when you detect a change in that particular cell value.
    Greetings
    Jeanette

  • JTable inside JTable cell

    Hello. I'm trying to see if it's at all possible to have a JTable inside a JTable cell. I tried modifying those 'JButton inside JCell' examples, to no avail - it seems I didn't actually grasp the idea.
    so anyway - did anyone ever do that? have a table inside a table? anyone can point me in the right direction?
    thanks.

    Hello. I'm trying to see if it's at all possible to
    have a JTable inside a JTable cell. I tried modifying
    those 'JButton inside JCell' examples, to no avail -
    it seems I didn't actually grasp the idea.It is possible, but I think it would make things confusing for the user. What exactly are you wanting to display?
    >
    so anyway - did anyone ever do that? have a table
    inside a table? anyone can point me in the right
    direction?You need a custom renderer and custom editor and most likely custom TableModels for each table. There are row height issues as well, especially if the rows/columns of the inner tables are variable. The getValueAt() method will require some thought. What is the value associated with all the cells in the inner table?
    All in all, this is doable, but may not be desirable.
    >
    thanks.

  • Inserting cell inside JTable cell

    Hi!
    i want to insert another cell inside a JTable cell, so that they are both displayed.
    Is it possible to do that.

    I was thinking about something like the below. I have not tested it, so let me know if it works.
    public class TwoCellTableCellRenderer extends DefaultTableCellRenderer {
         public Component getTableCellRendererComponent(JTable table,
                Object value,
                boolean isSelected,
                boolean hasFocus,
                int row,
                int column) {
              JPanel panel = new JPanel();
              panel.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
              panel.add(new JTextField(), null);
              panel.add(new JTextField(), null);
              return panel;
         protected void setValue(Object value) {
              // DO SOMETHING HERE TO PARSE YOUR TWO VALUES
    public class YourTwoCellDataClass {
    yourTable.setDefaultRenderer (YourTwoCellDataClass.class,
         new TwoCellTableCellRenderer());

  • Indeterminate JProgressBar inside JTable cell

    I am able to put a JProgressBar inside a JTable cell, via a custom renderer to do so, however, I am unable to make the progress bar show the indeterminate animation. Any ideas? I calledbar.setIndeterminate( true ); and it doesn't seem to want to show. Is the JTable preventing it?
    (should I include more of my code?)

    Your JProgressBar is used to render the table cell only when that cell of the JTable needs to be rendered and the JProgressBar has no say in this.
    I don't know why you would want to do this but to do this I would set up timer that fired a tree model event to say that the content of the cell had changed. This would trigger the cell to be re-painted. I think, but I can't be sure, that you will not be able to use
    bar.setIndeterminate( true );
    You may have to craft your own progress bar to make this easy.

  • 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 get the JCheckBox value in JTable?

    I have a JTable with JCheckBox inside. How can I get the value when the user turn on or off the check? I need to do this when the user change the value.
    Thanks for any help.
    Renato

    Hi again,
    no - the datamodel is a class that implements the TableModel-interface - if you do not use your own model in JTable, an instance of DefaultTableModel is used - you can subclass DefaultTableModel and overwrite its setValueAt(...)-method. When you instantiate your JTable do it by passing your DefaultTableModel subclass to the constructor or in the way you do it right now and replace the default model with your model using the setModel(...)-method of JTable.
    greetings Marsian

  • Validating  JCombox value inside JTable

    Hi people.
    I have such a task I can't complete without your help.
    I have a JTable with JComboboxes attached as cell editors, just like in the tutorial.
    JCombos are editable, so user can select value or type something.
    My task is to evaluate what value the user is typed manualy, and if he typed something wrong roll back the editing.
    I don't really know from what point should I start...
    I know how to track chamges during ItemSelect, but got no idea how to track manual input and how to rollback it.
    Edited by: Crosswinder on Aug 27, 2010 12:11 AM

    If you want to keep the editor open, override stopCellEditing() in the CellEditor and return false on a invalid value.
    Or you can ignore the invalid value in TableModel#setValueAt().

  • JTable inside JTable cell: drag and drop

    Hello. I've table (let's call it ParentTable), which cells contain other table (NestedTable). NestedTable recieves all events (I can move cursor, select cells by mouse, scroll table). ParentTable have enabled Drag nad Drop (D'n'D). When no cells in NestedTable are selected D'n'D works fine. When I select some cell in NestedTable, D'n'D does't work � it forbids the operation. I think this is because NestedTable recieves D'n'D events, but D'n'D is disabled for it. How can I work around this? I don't want to enable D'n'D for each NestedTable (there are several reasons for this).
    The question is � can I pass to NestedTable all events, except of D'n'D ones?

    Yes, I use custom cell renderer and cell editor for ParentTable, which returns NestedTable.
    DnD turned on for the ParentTable, so when the NestedTable is active (some cells selected in it) it receives DnD events, which are turned off for it, and DnD doesn't work.
    Possible solution is to turn DnD for NestedTable (not for ParentTable), and i'll do this if it is impossible to make it work in current configuration.
    So the question is � is this possible do not pass DnD event to NestedTable ?

  • Can not show the JCheckBox in JTable cell

    I want to place a JCheckBox in one JTable cell, i do as below:
    i want the column "d" be a check box which indicates "true" or "false".
    String[] columnNames = {"a","b","c","d"};
    Object[][] rowData = {{"", "", "", Boolean.FALSE}};
    tableModel = new DefaultTableModel(rowData, columnNames);
    dataTable = new JTable(tableModel);
    dataTable.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(new JCheckBox()));
    But when i run it, the "d" column show the string "false" or "true", not the check box i wanted.
    I do not understand it, can you help me?
    Thank you very much!
    coral9527

    Do not use DefaultTableModel, create your own table model and you should implement the method
    getColumnClass to display the boolean as checkbox ...
    I hope the following colde snippet helps you :
    class MyModel extends AbstractTableModel {
              private String[] columnNames = {"c1",
    "c2"};
    public Object[][] data ={{Boolean.valueOf(true),"c1d1"}};
         public int getColumnCount() {
         //System.out.println("Calling getColumnCount");
         return columnNames.length;
    public int getRowCount() {
    //System.out.println("Calling row count");
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    data[row][col] = value;
    fireTableCellUpdated(row, col);

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

Maybe you are looking for

  • Will I lose my unlimited date plan if...

    ....I simply switch to a 4G LTE device? I am currently using a family members upgrade in order to switch to the iPhone 5. I am not upgrading on my account because I don't have an upgrade. I am simply switching phones. So will I still lose my unlimite

  • I'm generating an actionsript app with Flash, but I can't get the effects to display properly

    When I publish the app as CPU, the effects display, but the video runs choppy. When I generate it as GPU, the video runs fine, but no of the effects display.

  • What to do with apr

    There exists an out of date package in extra called apr.  It was originally there because we were using the old version of apache (1.3) but now apache 2.0 includes apr. I understand that development continues on apr seperate from apache and that they

  • Standard report to view customer master

    Hi all, Is there any Transaction code/ Reports to view all existing customer details... Thanx in advance. S.Ramesh

  • Should i go with a mac or ipad?

    I have an iPhone 4S and as it runs out of space fast due to the amount of photos I take, I want something that will connect well with it as my compaq laptop doesnt.