How to repaint a JTextArea inside a JScrollPane

I am trying to show some messages (during a action event generated process) appending some text into a JTextArea that is inside a JScrollPane, the problem appears when the Scroll starts and the text appended remains hidden until the event is completely dispatched.
The following code doesnt run correctly.
((JTextArea)Destino).append('\n' + Mens);
Destino.revalidate();
Destino.paint(Destino.getGraphics());
I tried also:
Destino.repaint();
Thanks a lot in advance

Correct me if I am wrong but I think you are saying that you are calling a method and the scrollpane won't repaint until the method returns.
If that is so, you need to use threads in order to achieve the effect you are looking for. Check out the Model-View-Contoller pattern also.

Similar Messages

  • How do I remove the inside border in a JScrollPane?

    I'm trying to embed a JTextArea inside a JScrollPane. Not sure if it matters, but the JScrollPane is inside a JSplitPane, i. e.
    JSplitPane js = new JSplitPane(...)
    JTextArea ta = new JTextArea();
    JScrollPane sp = new JScrollPane(ta);
    js.setBottomComponent(sp);Now when the whole thing is seen, a black border is drawn around the TextArea ta. How do I remove this? Doing sp.setViewportBorder(null) doesn't help. Please help! THX.
    Edited by: solletica on Jun 10, 2008 8:45 AM
    Edited by: solletica on Jun 10, 2008 8:50 AM

    The problem is seen ONLY when the neither scrollbar is visible, i. e. when the AS_NEEDED property is set on JScrollPane. When this happens, a black square border is visible around the JTextArea.
    However, when the vertical or horizontal scrollbars are shown, the portion of the border where the scrollbar appears isn't visible (or noticeable).
    Correct me if I'm wrong, but doesn't JComponent.setBorder() only set the OUTSIDE border of a JComponent? I want to eliminate the border being shown around the JTextArea (i. e. between the JTextArea's bounds and the JScrollPane).
    Edited by: solletica on Jun 10, 2008 9:24 AM

  • How can i put text/chars inside a text area inside a JScrollPane?

    ive tried:
    receipt.setText("blah blah") // but it does not work. all i get is still a blank text area inside a JScrollPane
    JTextArea receipt;
    JScrollPane sp;
    receipt = new JTextArea();
    sp = new JScrollPane(receipt,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

    mstrnew = new JButton //this should clear receipt
    if(evnt.getSource()==mstrnew)
                  order.setText("");
                  price.setText("");
                  total.setText("0.0");
                  cash.setText("");
                  change.setText("");
                  mstrtotal = 0;
                  JOptionPane.showMessageDialog(null,"              Starting New Transaction...","",JOptionPane.PLAIN_MESSAGE);    receipt.setText("");}
    else if(evnt.getSource()==vm1)
                  generate("           2pc. Chicken Strips Meal\n");
                  order.setText("2pc. Chicken Strips");
                  price.setText("61.0");
                  mstrtotal = Double.parseDouble(price.getText()) + Double.parseDouble(total.getText());
                  total.setText(String.valueOf(mstrtotal));
    // scrollpane part
                 receipt = new JTextArea();
                 receipt.setEditable(true);
                 //receipt.setLineWrap(true);
             up = "\n          YUM! Brands Corporation, Kentucky Fried Chicken ?\n                       KFC LaSalle Branch, Taft Ave., Manila\n\n           88788   TIN-209-670-390-002   REG VAT   POS#113\n           SN:41-HK170 All prices were subjected of 12% VAT.";
             mid = "\n\n";
             down = "\n";
             complete = up+mid+down;
             receipt.setText(complete);
             sp = new JScrollPane(receipt,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    public void generate(String z)
             mid += z;
             complete = up+mid+down;
        }Message was edited by:
    ice3d

  • How can I set position of a JTextArea inside a JPanel?

    Hi,
    I'm trying to add a JTextArea to a JPanel. It works as expected but what can I do to alter the position of the JTextArea inside the JPanel? Right now the JTextArea is centered and starting at the top of the JPanel. I would like it to, either start one row down, or be centered vertically, depending on what looks the best.
    Tried to mark as question, but that option is gone once the message is posted it seems.
    Edited by: Red_herring on Nov 23, 2009 11:15 AM

    JPanels don't have "rows", so that probably isn't the best description of your requirement. But the short answer is that you do it with a LayoutManager. There's a tutorial about them. Google keywords: java layoutmanager tutorial, and look for the ones from Sun.

  • Centering a JComponent inside a JScrollPane

    I've got an instance of a subclass of JComponent (DrawCanvas) inside an instance of JScrollPane (scpEasel). scpEasel is itself in an instance of JInternalFrame (ifEasel) that used a GridLayout.
    When the DrawCanvas object can fit inside the JInternalFrame, it needs to be centered inside the JScrollPane object. If the canvas is wider than the window, it must be centered vertically. If it has a greater height than the window, it must be centered horizontally. When the canvas is, both horizontally and vertically bigger than the window, no centering is needed.
    I made a subclass of ScrollPaneLayout that does just that, but when only one of the scrollbars is visible, it doesn't want to scroll (whether I click on the arrows, or drag the box, etc.).
    How do I keep the scrollbars from jamming?
    Here's the code to the instance of ScrollPaneLayout:
    EaselLayout = new ScrollPaneLayout() {
        public void layoutContainer(Container parent) {
            super.layoutContainer(parent);
            Component Canvas = parent.getComponent(0);
            JScrollBar HSB = getHorizontalScrollBar(),
                       VSB = getVerticalScrollBar();
            int scpWidth = parent.getSize().width,
                scpHeight = parent.getSize().height,
                cX = Canvas.getLocation().x,
                cY = Canvas.getLocation().y,
                cWidth = Canvas.getPreferredSize().width,
                cHeight = Canvas.getPreferredSize().height;
            if (!HSB.isVisible() && !VSB.isVisible()) {
                Canvas.setLocation((scpWidth / 2) - (cWidth / 2), (scpHeight / 2) - (cHeight / 2));
            } else if (!HSB.isVisible()) {
                Canvas.setLocation((scpWidth / 2) - (cWidth / 2), cY);
            } else if (!VSB.isVisible()) {
                Canvas.setLocation(cX, (scpHeight / 2) - (cHeight / 2));
    };Please respond ASAP. Thanx.

    Please, I beg of you...someone help!!
    Here I have created a LayoutManager that is to be used within a JViewport to solve the issue of Centering the JComponent inside a JScrollPane.
    However, it works every time except the first time.
    The code for this LayoutManager (called CenteredLayoutManager) is in the first class.
    The second and third classes provide an application I wrote to test it.
    You type an integer value representing the percentage you want to zoom and press ENTER. The DrawingPanel will zoom the image for you.
    But, as you can see, the first time the image is in the upper left hand of the frame. All the other times, it is centered, but not the first time.
    Could someone explain why it doesn't do it the first time?
    Thank you for your help.
    // standard imports
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.JTextComponent;
    * A Layout that handles centering if the view is smaller than the
    * JViewPort.
    final class CenteredViewportLayout extends ViewportLayout
       private Rectangle clientArea = new Rectangle(),
       parentArea = new Rectangle();
       private Dimension dimens = new Dimension();
        * This does the centering for the layout.
       public void layoutContainer(Container p)
          JViewport parent = (JViewport)p;
          JComponent client = (JComponent)parent.getView();
          SwingUtilities.calculateInnerArea(parent, parentArea);
          clientArea.setBounds(parentArea);
          clientArea.setSize(client.getPreferredSize());
           * If the client is smaller than the parent scrollPane, then center it
           * within the parent. Otherwise, do the normal thing.
          if (parentArea.contains(clientArea))
             Point point = new Point((clientArea.width/2) - (parentArea.width/2),
                                     (clientArea.height/2) - (parentArea.height/2));
             parent.setViewPosition(point);
             parent.setViewSize(parent.getSize(dimens));
          else
             super.layoutContainer(p);
    class DrawingPanel extends JComponent implements Scrollable
       BufferedImage origImage;
       double        theZoom;    // the zoom factor
       Dimension     unitScroll; // used for correct scrolling...
       public DrawingPanel(BufferedImage img)
          origImage = img;
          unitScroll = new Dimension();
          zoomMe(100);
        * Changes the zoom factor.
        * @param val  the percentage of the zoom.
       public void zoomMe(int val)
          if (val < 1) val = 100;
          theZoom = val / 100.0;
          Dimension d = new Dimension((int)(origImage.getWidth()   * theZoom),
                                      (int)(origImage.getHeight()  * theZoom));
          unitScroll.setSize(d.width / 10, d.height / 10); // scroll 1/10 the way.
          setPreferredSize(d);
          revalidate();
       // EXTENDS JComponent
       // Draws the zoomed image.
       public void paintComponent(Graphics g)
          super.paintComponent(g);
          if (Math.abs(theZoom - 1) > 0.01)
             Graphics2D g2 = (Graphics2D)g;
             g2.scale(theZoom, theZoom);
          g.drawImage(origImage, 0, 0, null);
       // IMPLEMENTS Scrollable
       public Dimension getPreferredScrollableViewportSize()
          return getPreferredSize();
       public int getScrollableUnitIncrement(Rectangle visibleRect,
             int orientation,
             int direction)
          return (orientation == SwingConstants.HORIZONTAL) ? unitScroll.width :
                                                              unitScroll.height;
       public int getScrollableBlockIncrement(Rectangle visibleRect,
                                              int orientation,
                                              int direction)
          return (orientation == SwingConstants.HORIZONTAL) ? visibleRect.width :
                                                              visibleRect.height;
       public boolean getScrollableTracksViewportWidth() { return false; }
       public boolean getScrollableTracksViewportHeight() { return false; }
    * Main class.
    * @author J. Logan
    * @since 1.0 (2003-11-04)
    public class IndexColorTest
       // CONSTANTS
       static final IndexColorModel BASIC_COLOR_MODEL;
       // STATIC METHODS
       public static void main(String [] args)
          JFrame f  = new JFrame("ImageTest");
          f.setSize(400, 400);
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          final BufferedImage img = createImage(100, 100);
          final DrawingPanel p = new DrawingPanel(img);
          // This is me using the new layout for the scroll pane's viewport.
          JScrollPane jsp = new JScrollPane();
          JViewport vp = jsp.getViewport();
          vp.setLayout(new CenteredViewportLayout());
          jsp.setViewportView(p);
          f.getContentPane().add(jsp);
          // This is the text field you use to change the zoomed value.
          JTextField jtf  = new JTextField("100", 3);
          jtf.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent evt)
                      JTextComponent c = (JTextComponent)evt.getSource();
                      int val = Integer.parseInt(c.getText());
                      p.zoomMe(val);
          f.getContentPane().add(jtf, BorderLayout.NORTH);
          f.setVisible(true);
        * This just creates the image to be used in the zooming.
       private static BufferedImage createImage(int width, int height)
          BufferedImage img = new BufferedImage(width, height,
                                                BufferedImage.TYPE_BYTE_INDEXED,
                                                BASIC_COLOR_MODEL);
          DataBufferByte db = (DataBufferByte)img.getRaster().getDataBuffer();
          byte [] data = db.getData();
          int val = 0;
          for (int i = 0, max = data.length; i < max; ++i)
             val = i % 100;
             if ( val < 25 ) data[i] = 60;
             else if (val < 50)  data[i] = 120;
             else if (val < 75)  data[i] = (byte)180;
             else data[i] = (byte)240;
          return img;
       // This block just creates the ColorModel to use...unimportant for
       // question.
       static
          final byte [] colors = new byte[256];
          final int start = 20, end = 256;
          final double ratio = ((end) - start) / (double)(colors.length - 1);
          double val = start;
          for (int i = 1, max = colors.length; i < max; ++i)
             colors[i] = (byte)(val += ratio);
          BASIC_COLOR_MODEL = new IndexColorModel(8, colors.length,
                                                  colors, colors, colors);
    }Can someone please tell me why it does not work the first time.
    Thanks for your help.

  • Setting the value of a JScrollBar inside a JScrollPane not working.

    I have a display area (JPanel) inside a JScrollPane. What i want to do is that every time the user closes my application a file is saved with some preferences, like position and size onscreen, and the values of the scrollbars. My problem is that when I try to set the values of the JScrollBars, they seem to be completely ignored.
    I made a small class to illustrate this:
    import java.awt.*;
    import javax.swing.*;
    public class ScrollExample extends JFrame
         private JPanel display;
         private JScrollPane displayScroll;
         public ScrollExample()
              display = new JPanel();
              display.setPreferredSize( new Dimension( 800, 600 ) );
              displayScroll = new JScrollPane( display );
              add( displayScroll );
              setSize( 400, 300 );
              setVisible( true );
              displayScroll.getHorizontalScrollBar().setValue( displayScroll.getHorizontalScrollBar().getMaximum() );
         public static void main( String args[] )
              new ScrollExample();
    }The behaviour of is as intended. However if we switch the two lines to be:
    displayScroll.getHorizontalScrollBar().setValue( displayScroll.getHorizontalScrollBar().getMaximum() );
    setVisible( true );and launch it, the scrollbar appears to have moved only a small amount. This leads me to believe that it has something to do with the main window being visible. In my actual application, this call to setValue is ignored, unlike in this sample one. Even placing it after the setVisible call, it does not do anything.
    When I tried to use:
         Runnable doScroll = new Runnable()
                 public void run()
                      taskDisplayScroll.getHorizontalScrollBar().setValue( 200 );
             SwingUtilities.invokeLater(doScroll);after the setVisible call, as mentioned on http://forum.java.sun.com/thread.jspa?threadID=723424, it rarely (maybe 3 out of 20 times) sets the scrollbar to the indicated value.
    My question is this: What does the setValue() call depend on to run properly, and how do I code it to work in my program?
    If you need any additional information, please ask.
    Note: In the sample class I provided, the scrollbar moves to its proper spot, I could not cause it to not move at all, as is the case in my application that seems to have the same calls.
    Thanks, Serge.
    Edited by: super_serge on Jun 26, 2008 8:23 AM

    Can you please explain to me how b) would be implemented.Read the Swing tutorial on Concurrency for the new approach in JDK1.6, or I still prefer to use SwingUtilities.invokeLater for somthing simple like this.

  • Invisible JTextArea in a JScrollPane

    I want to have an invisible JTextArea in a JScrollPane (i only want a thin border either vieport border or JTextArea border). i tried setOpaque(false) for JTextArea, JScrollPane and both, and it wont work, i dont know why. Could anyone help me?

    This poster is 0 for 3 in responding to previous postings he has made.I did notice - that's why I didn't post the link.
    he/she might now learn how to do a search (for when future questions are ignored)
    What do you think the chances are he'll bother to thank anyone for the help
    he received on this posting?Nil
    a 'thank you' does go a long way to getting the next query answered, but I'd prefer just
    an acknowledement of "it works/doesn't work" - makes it so much easier, when
    searching the forums, when you spot a "yes, that works" at the end.

  • JTextPane inside a JScrollPane: any way to display a certain section?

    I have a GUI with a JTextPane inside a JScrollPane.
    The text of the JTextPane is the contents of a text file, so it typically has many lines.
    I want the JScrollPane (whose preferred size has already been previously set to display 11 rows of text) to always show one target line as the middle row, and the 5 rows before and after it as the remaining 10 rows.
    In other words, I want to show a certain line and its surrounding context.
    Do you guys know how to achieve this? I have already tried calling
    JTextPane.setCaretPositionbut this is inadequate because it merely guarantees that the line with the caret is visible--but it does not guarantee to center the caret line in the middle of the JScrollPane.
    I also tried calling
    textPane.scrollRectToVisible( textPane.modelToView(caretPos) );where textPane is my JTextPane, but this failed completely (seems to always display the final lines of the file).
    Anyone have any suggestions?

    Daryl: thanks for your response.
    My original code looked like this:
    int caretPos = 0;
    for (int i = 0; i <= index; i++) {
         caretPos += lines.length();
    textPane.setCaretPosition(caretPos);
    With *just* the above, you get the behavior that I originally described, namely, the line in question (which is lines[index]) always gets displayed, but it is not necessarily in the middle of the JScrollPane.
    I tried commenting out the line above which calls setCaretPosition, and used essentially your code instead:Rectangle caretRectangle = textPane.modelToView(caretPos);
    Rectangle viewRectangle = new Rectangle(
         0, caretRectangle.y - (scrollPane.getHeight() - caretRectangle.height) / 2,
         scrollPane.getWidth(), scrollPane.getHeight()
    textPane.scrollRectToVisible(viewRectangle);This fails too: the JScrollPane now always shows the bottom of the JTextPane.
    What does work is to use *both* techniques, namely, call setCaretPosition as well as scrollRectToVisible:     // set the caret to the line in question (i.e. at index); this merely guarantees that this line is visible, but not necessarily centered
    int caretPos = 0;
    for (int i = 0; i <= index; i++) {
         caretPos += lines[i].length();
    textPane.setCaretPosition(caretPos);
         // and IN ADDITION cause scrollPane's viewport to be centered around the line
    Rectangle caretRectangle = textPane.modelToView(caretPos);
    Rectangle viewRectangle = new Rectangle(
         0, caretRectangle.y - (scrollPane.getHeight() - caretRectangle.height) / 2,
         scrollPane.getWidth(), scrollPane.getHeight()
    textPane.scrollRectToVisible(viewRectangle);The interesting question is why do you need to do both steps?
    I think that I know the reason, but I would love to see someone confirm or deny this.  What follows is my speculation.
    The above code is inside a method that is call by a run method of the class in question which is always executed by the event dispatch thread (EDT), so it is not an illegal thread use case.  However, in the method that has the code above, I am clearing all existing text of the JTextPane and then repopulating it (with that String[] lines used above, which came from parsing a file).
    Now, in  [this posting|http://forums.sun.com/thread.jspa?messageID=10289999#10289999], camickr claimed:
    "When text is inserted into a Document, behind the scenes a call to setCaretPosition() is made to position the caret after the newly inserted text. However inserting text into a document is a complex procedure since Elements need to be created as the text inserted into the Document is parsed. So the call to the setCaretPosition() method is placed in a SwingUtilities.invokeLater(), which means tha code gets added to the end of the GUI EDT to be executed once the Document is in a complete state. So basically what is happening is that your call to set the view position does execute, but then is gets overridden by the setCaretPosition() method call."
    If the above claim is true, then all the calls in that method to add the file's text result in implicit calls to setCaretPosition which will be executed AFTER the method above ends (i.e. asynchronously, later on by the event dispatch thread).  Hence, I need to do an explicit setCaretPosition call of my own to override these implicit calls.
    Now, I am not sure that I totally buy this explanation.  I would like to see more proof of camickr's claims for one: I did a quick code review of some of the classes involved, and do not see where calling AbstractDocument.insertString generates an implicit call to setCaretPosition on the EDT.  To be sure, the code is complex, and I do not know where exactly to look, and maybe this is done by some listener or something, who knows.  Furthermore, my explicit call to setCaretPosition is done synchronously on the EDT (recall: that method above in my class is called by its run which is executed by the EDT).  So, my explicit call to setCaretPosition should occur in time before all of those delayed implicit calls, and thus should actually be overridden by them, no?
    I would love to hear from someone who really knows Swing...                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

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

  • How does repaint work?

    Can anybody tell me how does repaint work.

    hmm
    raheel_siddiqi = mraheel.
    Smart way of transferring Dukes (and earning more
    Dukes).
    Irrelevant question asked --> Posted in wrong forum
    --> STOOPID answer given ---> Dukes transferred.Very well pointed.... ;(
    >
    raheel bhai.. yeh baccho ka khel nahi hai :)Well Said :-)

  • How do i delete cookies inside my program????

    I have a login page. I want to check whether cookies are available, if any for this user or not? And if available i want to delete previous one's. How do I do this inside my program???? Can any body help me on this issue??????? pls.
    Thanks $ Regards
    Shashi

    Search javax.servlet.http.Cookie API for that.
    You can search cookies with getCookies method in the HttpServletRequest
    You delete your cookie setting it a max age value of 0
    setMaxAge(0)

  • How to use Java code inside WebDynpro-ABAP

    Hi,
        How to use Java code inside WebDynpro-ABAP.
    Could any one provide sample code.
    Cheers,
    Sam

    Hi Sam,
    We can't Bring Java Inside the ABAP. Both are running in different Environments.
    and also ABAP Codes are runs on BASIS.
    -Basis is a middleware between ABAP codes and Ur OS.
    -Contains set of programs to load,RUN,intepret the ABAP program..
    So Both are Different.
    Regards,
    Ramganesan K.

  • HOW TO CALL FUNCTION MODULE INSIDE SMARTFORM

    PLEASE ANYONE TELL ME, ABOUT  HOW TO CALL FUNCTION MODULE INSIDE SMARTFORM. IT IS VERY URGENT!!!!!!!!!1

    Hi,
      Under Global Definitions, we have 'Form Routines' tab. Under this tab, u can have a dynamic subroutine call. With in FORM and ENDFORM, you can call the Function Module.With in the Program Lines editor, u can define the subroutine........PERFORM. 
    If helpful, reward points.
    Rgds,
    CK

  • How to clean the dust inside the screen of the iPod Touch?

    Hi everybody,
    lately some dust entered inside the screen of my iPod Touch.
    At first it looked like one or two pixels were gone bad, but it is just some annoying dust.
    The problem is that I cannot figure out any way to remove it.
    I tried a gentle blow from the connector hole but the result was worse.
    Any idea on how to clean the screen inside?
    I hope it is not necessary to go to an Apple Center and pay for the "cleaning service".
    Regards,
    Andrea

    It sounds safe to use
    'Falcon's® "Professional" Dust-Off® "XL" compressed-gas is the perfect product for removing dust from your color transparencies before making scans or copy slides; it's also great for removing dust from cameras, lenses, computers and other electronic equipment. Each 12 oz. disposable can comes with its own trigger value and a 4.75" nozzle extension (a red tube) that allows you to place precise bursts of compressed air just where you want it.'
    Check the directions on the back... also check the contents. Normally anything like that will inform you of contaminants harmful to delicate electrical devices.
    If its just compressed air make sure you keep the can well back from the source.. and unplug the G5 (take it somewhere you don't mind dust.. there no point doing this in situe, just for it to suck it back in again!)
    Also.. as mentioned.. keep the can upright (as the air is decompressed the can gets very cold)
    Stu
    Powermac G5 2.5 Mac OS X (10.4.2) 460gb HD 3gb RAM

Maybe you are looking for

  • Displaying image from database in report

    I need to include a picture (company logo) in numerous reports. This logo will be stored in an MS SQL Image field in a table (this bit I have already sorted out). What I'm wondering is, what is the best way to retrieve this image from the database? D

  • Initial Load of BUPA_MAIN  to GWA_01 does not work

    Hi all I have a question concerning the serverside groupware Integration and the initial Load of BUPA_MAIN. According to the groupware integration guide, I have to "Transfer Business Partner to Public Contact Directory". This is done with transaction

  • GRIR Clearing - Assigment Feild to be replaced by PO numbers.

    Dear Friends, We have a very peculiar situation, whereby in the GR/IR Clearing Account, the sort key was mentioned as 001 (Posting Date), instead of 014 - Purchase Order + Item. The result is that in the Assignment Feild instead of Purchase Order No.

  • Sidecar.xml help

    I've never created a sidecar.xml file before, but with the new update to the folio builder I want to update this way vs. doing all the articles manually. I think I did something wrong because after importing the xml file nothing happens, this is what

  • Can't download Adobe Air

    Hello, recently I installed a fresh copy of Windows 7 Home Premium (X86) and attempted to install photoshop as soon as I got it done. Well, in order to install Adobe Photoshop I must download Air with the download assistant, but whenever I navigate t