Focus in JTextArea (JDK1.4)

hi,
I try to tab in a JTextArea when I use JDK 1.4. But new focus traversal policy in JDK 1.4 does not include JTextArea. Anybody has any idea how to do this: the focus should be on the selected line or the first line by default whenever pressing Tab key into a JTextArea? Thanks anyway.

hi,
maybe when you reactivate the browser, you reactivate the site(!) and not the applet.
The applet is only a part of the site and has to be activated, too.
I guess this is the problem.
but i got no idea how to fix this.
sorry.
cu Errraddicator

Similar Messages

  • How to create a custom focus manager in jdk1.4

    Dear All,
    I'm now trying to create a form for user to submit data. The key tab are easily to tab between textfields in html, you can set whatever order you want. But when I tried to create a form using java, I found very hard to do so. Any reference link and examples are appreciate.
    Thanks in advance
    Kitty

    cat8888,
    In general, tab-order is usaually the order you've added to the Panel / JPanel. When Panel is added to Panel and that to Panel and so on, sometimes the order can become less clear. When "trapped" inside a TextArea / JTextArea, the tab key takes on it's own meaning and now it wants to tab inside the TextArea. For this, you'll need special coding. For example, you might try adding code like this:
    myTextAreaObject.addKeyListener( new KeyAdapter() {
    public void keyPressed(KeyEvent ke) {
    if ( ke.getKeyCode() == ke.VK_TAB ) {
    myNextButtonObject.requestFocus();
    ... which effectively forces focus on - in this case - the JButton following the JTextArea.
    Not sure if this is what you mean, but HTH. And by the way, if someone has a neater way t odo this, I'd also like to know.
    ~Bill

  • Need focus in JTextArea

    Hai Friends,
    I am on the way of developing a QUERY ANALYSER. Mean while i got a problem. in my product I am using two JTabbedPanes(1 & 2).
    In TabbedPane1 i have a text area (to write the query) and the tabbedpane2 on which two panes( one for dispaying the result on a JTable and other for displaying messages.).
    On running my application I like to see the cursor blinking on the JTextArea.
    How it can be possible?
    Do you like to need some more explanation?
    some one help me.....
    Tino Simon.
    .

    Try this :
    mytextarea.requestFocus();
    to give focus to your textarea called "mytextarea"

  • Problematic focus traversal (JTextArea)

    I have a data entry dialog with several JTextFields and one JTextArea.
    Focus traversal (with the tab key) works nicely between instances of JTextField, but it is not possible to tab out of the JTextArea to the next JTextField (as a tab is inserted in the text area instead). I've have looked up swing focus traversal in books, but no cigar when it comes to dealing with JTextAreas
    Does anyone know how to fix this? I don't need to enter tabs into the text area.
    thanks,
    Andy

    There is a Swing forum for Swing related questions.
    Have you tried searching the forum?. Using keywords "+jtextarea +tab" would be a good place to start. You'll be amazed how many times this question has been asked/answered before.
         This example shows two different approaches for tabbing out of a JTextArea
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TextAreaTab extends JFrame
         public TextAreaTab()
              // Reset the FocusManager
              JTextArea textArea1 = new JTextArea(5, 30);
              textArea1.setText("1\n2\n3\n4\n5\n6\n7\n8\n9");
              JScrollPane scrollPane1 = new JScrollPane( textArea1 );
              getContentPane().add(scrollPane1, BorderLayout.NORTH);
              textArea1.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null);
              textArea1.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null);
              scrollPane1.getVerticalScrollBar().setFocusable(false);
              scrollPane1.getHorizontalScrollBar().setFocusable(false);
              //  Replace the Tab Actions
              JTextArea textArea2 = new JTextArea(5, 30);
              textArea2.setText("1\n2\n3\n4\n5\n6\n7\n8\n9");
              getContentPane().add(new JScrollPane(textArea2), BorderLayout.SOUTH);
              InputMap im = textArea2.getInputMap();
              KeyStroke tab = KeyStroke.getKeyStroke("TAB");
              textArea2.getActionMap().put(im.get(tab), new TabAction(true));
              KeyStroke shiftTab = KeyStroke.getKeyStroke("shift TAB");
              im.put(shiftTab, shiftTab);
              textArea2.getActionMap().put(im.get(shiftTab), new TabAction(false));
         class TabAction extends AbstractAction
              private boolean forward;
              public TabAction(boolean forward)
                   this.forward = forward;
              public void actionPerformed(ActionEvent e)
                   if (forward)
                        tabForward();
                   else
                        tabBackward();
              private void tabForward()
                   final KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
                   manager.focusNextComponent();
                   SwingUtilities.invokeLater(new Runnable()
                        public void run()
                             if (manager.getFocusOwner() instanceof JScrollBar)
                                  manager.focusNextComponent();
              private void tabBackward()
                   final KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
                   manager.focusPreviousComponent();
                   SwingUtilities.invokeLater(new Runnable()
                        public void run()
                             if (manager.getFocusOwner() instanceof JScrollBar)
                                  manager.focusPreviousComponent();
         public static void main(String[] args)
              TextAreaTab frame = new TextAreaTab();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);

  • Query on Focus feature of jdk1.4

    My awt code(jdk1.1.8) in the applet does not display the content on the panel unless the mouse is focussed/moved on it. This problem I observed only when I use JPI1.4. It works with JPI1.3
    I found from
    http://java.sun.com/j2se/1.4/compatibility.html
    from pt 19 that jdk1.4 has new Focus feature where one has to set
    component.setFocusTraversalKeysEnabled(false);
    I did try this . But that did not work. To which component mean this
    setFocusTraversalKeysEnabled(false) has to be put.
    Is it to the parent that is top level frame to which panels are attached.
    Correct me if I am wrong

    I would suggest upgrading OWB to 10.1 at the least or the current 10.2 version. These are certified with 10g databases. Even though your maps seem to work you are probably running in an unsupported environment.
    The upgrade of OWB should be relatively painless although I have not done that particular upgrade personally. Maybe others can comment on that process.
    Good luck.
    -gary

  • Moving the Focus with the TAB key in a JTextArea Component

    Dear Friends,
    I have exhausted all options of moving focus from JTextArea to next component. I have also tried all suggestions available in this forum. But i'm not able to solve my problem. Can any one help me.
    Thanx in advance.

    I had the same problem before. Here is what i did.
    JTextArea txtArea = new JTextArea(2,15);
    Set forwardTraversalKeys = new HashSet();     
    forwardTraversalKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));          
    txtArea.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,forwardTraversalKeys);          
    Set backwardTraversalKeys = new HashSet();          
    backwardTraversalKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK));          
    txtArea.setFocusTraversalKeys( KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, backwardTraversalKeys);
    JScrollPane scrollPane = new JScrollPane(
         txtArea,
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    // the scrollbar of the JScrollPane is focusable that's why it requires
    // another TAB key to transfer the focus.
    scrollPane.getVerticalScrollBar().setFocusable(false);

  • Focus with JTable - JDK 1.4

    Hi all, I wonder if there's anyone out there know about focus change on jdk1.4, please help me on this if you can:
    with jdk 1.3, when I change focus between components on the same panel, I override this method of JTable to stop focus from being on table's rows only when the table has Focus since it does not move focus to the next component on the panel:
    public boolean isManagingFocus() {
    return false;
    But when I use jdk 1.4 now, this method seems not work as expected anymore. The focus is now switch just between the rows when table has the focus and it does not move the focus to the next components on the panel when I hit TAB key.
    If anyone knows how to fix this, please help me through. Anyhelp will be very appreciated.
    CL

    Sorry it's late but here goes.
    isManagingFocus is deprecated in 1.4 so it's probably best not to use that anyway. It's also called from the constructor of JComponent so if it uses instance variables you might get things like NullPointerException if you're not careful.
    I think the recommended way to approach it is to set the focus traversal keys something like this
    // get your table from somewhere
    JTable table = new JTable();
    // use java.awt.AWTKeyStroke to set up the appropriate focus
    // traversal keys
    AWTKeyStroke tab = AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB, 0);
    AWTKeyStroke shiftTab = AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB, KeyEvent.SHIFT_DOWN_MASK);
    AWTKeyStroke ctrlTab = AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB, KeyEvent.CTRL_DOWN_MASK);
    AWTKeyStroke ctrlShiftTab = AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB, KeyEvent.CTRL_DOWN_MASK | KeyEvent.SHIFT_DOWN_MASK);
    // create a java.util.Set for forwards and backwards focus traversal
    // keys. The actual concrete Set you use probably doesn't matter.
    // I've used a java.util.HashSet
    HashSet forwardKeys = new HashSet();
    HashSet backwardKeys = new HashSet();
    // add the appropriate keys to the appropriate sets
    forwardKeys.add(tab);
    forwardKeys.add(ctrlTab);
    backwardKeys.add(shiftTab);
    backwardKeys.add(ctrlShiftTab);
    // set the focus traversal keys on the table.
    table.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, forwardKeys);
    table.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, backwardKeys);

  • JTextPane & JTextArea Control Handling

    Hello...
    I have created chat application. At client side i take applet in that The chat is dispalyed in JTextPane in different colors. Also i have taken JTextArea & button to send message to other end. But the problem is that when chat message is receives from remote end it is shown in JTextPane & if at same time user is typing message in JTextArea then focus is lost from JTextArea to JTextPane. This action prevents user from writing he has to set focus on JTextArea again & again.
    The code is
    StyledDocument doc = (StyledDocument)jtp.getDocument();                 
                   doc.insertString(doc.getLength(), "\n"+oprName+": "+matter, style2); Help plz.....

    This is a bit of a guess but you may well find that my suggestion in this thread (apply it to your display component rather than the input component) fixes it,
    http://forum.java.sun.com/thread.jspa?threadID=5114287
    If not then you should be able to follow the source code from setText() to see what's grabbing the focus.

  • Does JOptionPane have a bug in jdk1.4?

    Sorry to post this again, but last time had posted it under a different title/topic. The following piece of code works fine with jdk1.3, but HANGS with jdk1.4-import java.awt.event.*;
    import javax.swing.*;
    public class TestDriver extends JPanel {
       JTextField textField1, textField2;
       MyInputVerifier inputVerifier;
       public TestDriver() {
          initPanel();
       private void initPanel() {
          textField1 = new JTextField(10);
          textField1.setName("Test");
          textField2 = new JTextField(10);
          this.add(textField1);
          this.add(textField2);
          inputVerifier = new MyInputVerifier();
          textField1.setInputVerifier(inputVerifier);
       public static void main(String[] args) {
          JFrame frame = new JFrame();
          frame.getContentPane().add(new TestDriver());
          frame.setSize(200, 100);
          frame.setVisible(true);
          frame.addWindowListener(new WindowAdapter() {
             public void windowClosing(WindowEvent e) {
                System.exit(0);
       class MyInputVerifier extends InputVerifier {
          public boolean verify(JComponent comp) {
             //only when the user enters "Test" in the first text field, should the focus be
             //transferred to the next text field
             if(comp.getName().equals("Test")) {
                String text = ((JTextField)comp).getText();
                if(("Test").equals(text)) {
                   return true;
                } else {
                   showError();
                   return false;
             return true;
       private void showError() {
          //this works fine with both jdk1.3 and jdk1.4
          System.out.println("Wrong!\n Enter \"Test\"");
          //this is where the program hangs when run with jdk1.4
          JOptionPane.showMessageDialog(this, "Wrong!\n Enter \"Test\"");
    }Can anyone please confirm that it really doesn't work with jdk1.4? Also please let me know if anything is wrong with the program.
    I searched in the bug database and found that a few bugs on similar topics have already been reported. But I didn't find one (which is open) particularly on this topic. Is anyone aware of a bug on this topic already reported? If so, could you please post the appropriate link here.
    Thanks a lot.

    Thanks for the reply. The problem is not related to JOptionPane. It's related to verify method of InputVerifier. First of all, as per the jdk1.4 Javadocs, the verify method is not allowed to have side effects. So calling JOptionPane.showMessageDialog() from within verify is not a correct implementation. But the javadocs say that shouldYieldFocus of InputVerifier is allowed to have side effects. So basically the shouldYieldFocus method needs to be implemented and it should pou up a dialog when the input is incorrect.
    BUT, it doesn't work either. It has a bug (4532517). Here is the link to the related bug report-http://developer.java.sun.com/developer/bugParade/bugs/4532517.html
    A workaround has been given there and after using that, the program works fine.
    I have no idea, why it works fine with 1.3. As you said, due to changes in the Focus mechanism in jdk1.4, this problem has arisen.
    Thanks.

  • How to gain focus on JLabel

    hi all,
    My question is how can i gain a focus on JTextarea when mouse click on it.
    any hits are welcome.Thanks in advance.
    Message was edited by:
    cocoonwls
    Message was edited by:
    cocoonwls
    Message was edited by:
    cocoonwls

    I am not sure why you would want focus on a label, but if you do, add the jlabel to a mouselistener and when you click, write, "jlabel.requestFocus()".

  • JDK 1.6 JavaScript problem

    I'm not sure if this is the correct forum to post this, if not please let me know where I should be asking.
    I have a problem with the Rhino 1.6r2-based javax.script JavaScript implementation included with JDK 1.6. I'm in a situation where I have a JavaScript object "a" with a function "x" defined on it. I embed my JavaScript into Java, and I want to dynamically execute JavaScript code defined outside my control in the context of "a", including calling its "x" function.
    Due to the lack of explicit scope control in this implementation, I have a rather awkward way of making "a" the current context object. Essentially I define a new function "__func" on "a", the body of which is the arbitrary JavaScript I want to execute, as follows:
    String js = ...;
    engine.eval("a.__func = function() { " + js + " }");
    Now I can invoke the "__func" function in the context of "a":
    Object ret = ((Invocable)engine).invokeMethod(a, "__func");
    Experimentation shows that "this" in JavaScript resolves correctly to "a". I can list the members of "a" correctly using code such as
    for (var name in this) { java.lang.System.out.println(name); }
    The members of "a" includes "x", and "typeof" x is a function. No problem. However "x" cannot be resolved as is. That is, if my "js" variable above contains "java.lang.System.out.println(x.toString());" I get an error that "x" cannot be resolved, despite it being a member of "this". However, the following works correctly: "java.lang.System.out.println(this.x.toString());".
    Now, this seems like a bit of a bug to me, but it's entirely possible I'm going the wrong way about trying to set up the context object "a" in the first place. Anyway if anyone has any suggestions on how I can progress with this they would be much appreciated.

    I solved doing a different Focus manage.
    The memory goes full because at a point the focus policy (default) loose the main window. I don't know why, but forcing my main window be the FocusRoot all seems going good and the memory use goes normal.
    Now I've another similar problem (focus is not managed well with tablepanel enabled on the fly). Now I think the new focus system with JDK1.5 is really full of non compatibilities with older JDK! Good luck to all programmers extending the compatibility with this new release!
    Bye, Anteo.

  • JTable.getSelectedRow seems to return wrong index value in J2SDK 1.4

    OS version: Microsoft Windows 2000 [Version 5.00.2195]
    JDK version: J2RE, Standard Edition (build 1.4.2_07-b05)
    I have a pretty simple JTable in which when a user selects a particular value in the first column of a row, the remainder of the columns in that row are populated with text values. The way we tell the JTable which row to populate the column values for is via the getSelectedRow() method. This worked fine using 1.3.1.08. However, when we upgraded to 1.4.2.07, we get an ArrayIndexOutOfBoundsException thrown because for some reason the getSelectedRow method returns the wrong value (e.g. if the user selects the first row, instead of returning an index of 0, the method returns an index of 2, even if there is only 1 row in the table, thus the out-of-bounds). The code has not changed at all -- all we have done is upgrade the version of the JDK. I have seen similar issues on various postings on the web, but these all have to do with removing rows and the like, and having to cancel or stop cell editing before removing the row(s). However, this does not apply in my case, so I think this might be a new bug. Before I post all kinds of code, does anybody know if this is a known bug and/or is there a workaround?
    Here is my stack trace:
    In Thread[AWT-EventQueue-0,6,main]
    caught java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
         at java.util.Vector.elementAt(Vector.java:431)
         at javax.swing.table.DefaultTableModel.setValueAt(DefaultTableModel.java:633)
         at com.sra.kdd.tools.view.NtwrkDefnVW.propertyChange(NtwrkDefnVW.java:475)
         at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:330)
         at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:257)
         at com.sra.kdd.tools.model.NtwrkSourceDSMDL.setDsNM(NtwrkSourceDSMDL.java:298)
         at com.sra.kdd.tools.view.NtwrkCTRL.handleSourceTableEvent(NtwrkCTRL.java:464)
         at com.sra.kdd.tools.view.NtwrkCTRL.tableChanged(NtwrkCTRL.java:120)
         at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableModel.java:280)
         at javax.swing.table.AbstractTableModel.fireTableCellUpdated(AbstractTableModel.java:259)
         at javax.swing.table.DefaultTableModel.setValueAt(DefaultTableModel.java:635)
         at javax.swing.JTable.setValueAt(JTable.java:1794)
         at javax.swing.JTable.editingStopped(JTable.java:3167)
         at javax.swing.AbstractCellEditor.fireEditingStopped(AbstractCellEditor.java:124)
         at javax.swing.DefaultCellEditor$EditorDelegate.stopCellEditing(DefaultCellEditor.java:329)
         at javax.swing.DefaultCellEditor$3.stopCellEditing(DefaultCellEditor.java:139)
         at javax.swing.DefaultCellEditor.stopCellEditing(DefaultCellEditor.java:214)
         at javax.swing.DefaultCellEditor$EditorDelegate.actionPerformed(DefaultCellEditor.java:346)
         at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1197)
         at javax.swing.JComboBox.setSelectedItem(JComboBox.java:561)
         at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:597)
         at javax.swing.plaf.basic.BasicComboPopup$ListMouseHandler.mouseReleased(BasicComboPopup.java:749)
         at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:232)
         at java.awt.Component.processMouseEvent(Component.java:5100)
         at javax.swing.plaf.basic.BasicComboPopup$2.processMouseEvent(BasicComboPopup.java:452)
         at java.awt.Component.processEvent(Component.java:4897)
         at java.awt.Container.processEvent(Container.java:1569)
         at java.awt.Component.dispatchEventImpl(Component.java:3615)
         at java.awt.Container.dispatchEventImpl(Container.java:1627)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3198)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
         at java.awt.Container.dispatchEventImpl(Container.java:1613)
         at java.awt.Window.dispatchEventImpl(Window.java:1606)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)
    I do have a workaround -- this is definitely not a recommended workaround whatsoever, but it's what I've done just to get by for now, so I thought it might possibly shed some light into the problem. It seems that the index is always off by 2, so I just subtract 2 from the result of getSelectedRow() and then everything works just fine.
    Any ideas? Thank you!

    If I remember correctly there was a big change in the focus subsystem between JDK1.3 and JDK1.4
    Before I post all kinds of code,...Write a 10 line demo program that shows this behaviour. We aren't interested in all kinds of code. If you can't duplicate the problem in 10 lines of code, then the problem is with the rest of your code. So compare you demo code to see why its working and your current code to see why its not working.

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

  • JTextField and JTextArea don't get focus occuasionally

    I am developing a Java Swing Applet. At edit mode, JComboBox, JCheckBox, JRadioBox, and JButton work fine, but JTextField and JTextArea can't get focus occuasionally while I click them.
    Anyone has idea?
    Thanks

    Thank you Himanshu,
    but that's not exactly what my issue is. This link describes the undesired effect of ending up outisde of the player window and in the browser.
    My problem is kind of the opposite. When I launch the page in the html file I cannot use the tab key to get to any of the controls in the captivate window. I'm stuck in the browser unless I click on the captivate window. That is not acceptable if we want it accessible without using a mouse. I found a way to make it work for chrome like I stated above, but not in FF. Do you have any ideas for this?
    Thanks!
    Monique

Maybe you are looking for

  • Ipod classic don't charge nor recognize by windows after itunes update

    Hi guys, Any solution to problem with the ipod classic and the latest version of itunes? I have the same problem as many other, my ipod classic don't charge nor is recongnize by my windows desktop, this start after I upgrade to itunes 7.6.1 Apple guy

  • Dynamic File name in IR bypass scenario

    Hi All, i have a scenario , where i am bypassing my IR part. i need to transfer image files from one location to another. Now i need to create the Directory as current date and Filename with what i have in sender file name. Any clue guyz?

  • Z60M Touchpad Right/Left Click Not Working

    I'm baffled.  I can move the pointer all day long with the touchpad, but I cannot select anything by tapping nor with the left and right buttons.  According the BIOS, everything with the ultranav seems normal and active.  I cracked open the palmrest

  • Inbound Calls Fail

    HI. I'm running CME on a 2851. My issue is with inbound calls not failing totally, but then requiring the extension to be dialed. This only happens for calls where the calling number is unknown. So all calls inbound work if the inbound calling number

  • How can I import Bookmark from Opera

    ''dupe of https://support.mozilla.org/en-US/questions/913887'' I want to import bookmark from opera browser. for that I follow the process- Bookmarks- Show all Bookmark- Import & Backup- Import Data From Another Browser- I choose Opera & Click Next b