Document Listener for JTextArea in JTable

I am trying to implement a DocumentListener for JTextArea in JTable, but its not happening.
Can someone tell me what's wrong. SSCCE below.
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.text.Document;
public class MyTable_TextArea extends JTable {
     private DefaultTableModel defaultTableModel;
     private Object[][] dataArray;
     private Object[] columnNameArray;
     public final int TEXT_COLUMN = 0;     
     // column headers
     public static final String TEXT_COLUMN_HEADER = "Text";
     // text area
     TextFieldRenderer3 textFieldRenderer3;
      * constructor
      * @param variableNameArray
      * @param columnNameArray
     public MyTable_TextArea(Object[][] variableNameArray, Object[] columnNameArray) {
          this.dataArray = variableNameArray;
          this.columnNameArray = columnNameArray;
          defaultTableModel = new DefaultTableModel(variableNameArray, columnNameArray);
          this.setModel(defaultTableModel)     ;
          // text field
        textFieldRenderer3 = new TextFieldRenderer3();
          MyDocumentListener myListener = new MyDocumentListener();
          textFieldRenderer3.getDocument().addDocumentListener(myListener);
        TableColumn modelColumn = this.getColumnModel().getColumn(TEXT_COLUMN);
          modelColumn.setCellRenderer(textFieldRenderer3);
      * nested class
     class MyDocumentListener implements DocumentListener {
         String newline = "\n";
         public void insertUpdate(DocumentEvent e) {
              System.out.println ("insert update");
             updateLog(e, "inserted into");
         public void removeUpdate(DocumentEvent e) {
              System.out.println ("remove update");
             updateLog(e, "removed from");
         public void changedUpdate(DocumentEvent e) {
             //Plain text components do not fire these events
         public void updateLog(DocumentEvent e, String action) {
             Document doc = (Document)e.getDocument();
             int changeLength = e.getLength();
             textFieldRenderer3.append(
                 changeLength + " character" +
                 ((changeLength == 1) ? " " : "s ") +
                 action + doc.getProperty("name") + "." + newline +
                 "  Text length = " + doc.getLength() + newline);
      * @param args
     public static void main(String[] args) {
          try{
               UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
          catch (Exception e){
               e.printStackTrace();
         String[] columnNameArray = {
                   TEXT_COLUMN_HEADER,
                   "1",
                   "2",
          Object[][]  dataArray = {      {"", "", ""},      };
          final MyTable_TextArea panel = new MyTable_TextArea(dataArray, columnNameArray);
          final JFrame frame = new JFrame();
          frame.getContentPane().add(new JScrollPane(panel));
          frame.setTitle("My Table");
          frame.setPreferredSize(new Dimension(500, 200));
          frame.addWindowListener(new WindowAdapter(){
               @Override
               public void windowClosing(WindowEvent e) {
          frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
          frame.setLocation(300, 200);
          frame.pack();
          frame.setVisible(true);
class TextFieldRenderer3 extends JTextArea implements TableCellRenderer {
     Icon defaultIcon;
     boolean isChecked = false;
     public TextFieldRenderer3() {
          System.out.println ("TextFieldRenderer()");
          setToolTipText("Double click to type");
     @Override
     public Component getTableCellRendererComponent(JTable table,
               Object value,
               boolean isSelected,
               boolean hasFocus,
               int row,
               int column) {
          System.out.println ("TextFieldRenderer.getTableCellRendererComponent() row/column: " + row + "\t"+ column);
          return this;
}

I've implemented in the cell editor. I don't see how to get the value being typed (and nothing appears in the text area)
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.EventObject;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.event.CellEditorListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.text.Document;
public class MyTable_TextArea extends JTable {
     private DefaultTableModel defaultTableModel;
     private Object[][] dataArray;
     private Object[] columnNameArray;
     public final int TEXT_COLUMN = 0;     
     // column headers
     public static final String TEXT_COLUMN_HEADER = "Text";
     // text area
     TextAreaEditor textAreaEditor;
      * constructor
      * @param variableNameArray
      * @param columnNameArray
     public MyTable_TextArea(Object[][] variableNameArray, Object[] columnNameArray) {
          this.dataArray = variableNameArray;
          this.columnNameArray = columnNameArray;
          defaultTableModel = new DefaultTableModel(variableNameArray, columnNameArray);
          this.setModel(defaultTableModel)     ;
          // text field
        textAreaEditor = new TextAreaEditor();
          MyDocumentListener myListener = new MyDocumentListener();
          textAreaEditor.getDocument().addDocumentListener(myListener);
        TableColumn modelColumn = this.getColumnModel().getColumn(TEXT_COLUMN);
          modelColumn.setCellEditor(textAreaEditor);
      * nested class
     class MyDocumentListener implements DocumentListener {
         String newline = "\n";
         public void insertUpdate(DocumentEvent e) {
              System.out.println ("insert update");
             updateLog(e, "inserted into");
         public void removeUpdate(DocumentEvent e) {
              System.out.println ("remove update");
             updateLog(e, "removed from");
         public void changedUpdate(DocumentEvent e) {
             //Plain text components do not fire these events
         public void updateLog(DocumentEvent e, String action) {
             Document doc = (Document)e.getDocument();
             int changeLength = e.getLength();
             textAreaEditor.append(
                 changeLength + " character" +
                 ((changeLength == 1) ? " " : "s ") +
                 action + doc.getProperty("name") + "." + newline +
                 "  Text length = " + doc.getLength() + newline);
      * @param args
     public static void main(String[] args) {
          try{
               UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
          catch (Exception e){
               e.printStackTrace();
         String[] columnNameArray = {
                   TEXT_COLUMN_HEADER,
                   "1",
                   "2",
          Object[][]  dataArray = {      {"", "", ""},      };
          final MyTable_TextArea panel = new MyTable_TextArea(dataArray, columnNameArray);
          final JFrame frame = new JFrame();
          frame.getContentPane().add(new JScrollPane(panel));
          frame.setTitle("My Table");
          frame.setPreferredSize(new Dimension(500, 200));
          frame.addWindowListener(new WindowAdapter(){
               @Override
               public void windowClosing(WindowEvent e) {
          frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
          frame.setLocation(300, 200);
          frame.pack();
          frame.setVisible(true);
class TextAreaEditor extends JTextArea implements TableCellEditor {
     Icon defaultIcon;
     boolean isChecked = false;
     public TextAreaEditor() {
          System.out.println ("TextAreaEditor()");
          setToolTipText("Double click to type");
     @Override
     public Component getTableCellEditorComponent(JTable arg0,
               Object arg1,
               boolean arg2,
               int arg3,
               int arg4) {
          System.out.println ("TextAreaEditor() arg1: " + arg1 + "arg2: " + arg2  + " arg3: " + arg3  + " arg4: " + arg4  );
          return null;
     @Override
     public void addCellEditorListener(CellEditorListener arg0) {
          System.out.println ("TextAreaEditor().addCellEditorListener");
     @Override
     public void cancelCellEditing() {
          System.out.println ("TextAreaEditor().cancelCellEditing");
     @Override
     public Object getCellEditorValue() {
          System.out.println ("TextAreaEditor().getCellEditorValue");
          return null;
     @Override
     public boolean isCellEditable(EventObject arg0) {
          System.out.println ("TextAreaEditor().isCellEditable");
          return true;
     @Override
     public void removeCellEditorListener(CellEditorListener arg0) {
          System.out.println ("TextAreaEditor().removeCellEditorListener");          
     @Override
     public boolean shouldSelectCell(EventObject arg0) {
          System.out.println ("TextAreaEditor().shouldSelectCell");
          return false;
     @Override
     public boolean stopCellEditing() {
          System.out.println ("TextAreaEditor().stopCellEditing");
          return false;
}

Similar Messages

  • JTable Document Listener for JTextField editor

    hello, how can I tell if removeUpdate in DocumentListener has been triggered by the user performing a delete in a JTextField or by the user cancelling a previous edit?
    example table
    | abc | def | ghi |<- user clicks in this cell which puts it in editmode
    | jkl | mno | pqr |<- user then clicks here which triggers removeUpdate for previous cell but how do I know this?
    Regards,
    b

    hello, how can I tell if removeUpdate in DocumentListener has been triggered by the user performing a delete in a JTextField or by the user cancelling a previous edit?
    example table
    | abc | def | ghi |<- user clicks in this cell which puts it in editmode
    | jkl | mno | pqr |<- user then clicks here which triggers removeUpdate for previous cell but how do I know this?
    Regards,
    b

  • Listener for selection in JTable

    Hello everybody,
    following problem. I have to check, if an selection in an JTable is valid or not. For this purpose I need to have a listener, which is invoked when a line or multiple lines of a JTable have been selected.
    Thanks for your help

    you can use myTable.addMouseListener() to add a listener to the table;
    then to get the row index where the event happened you can use:
    myTable.rowAtPoint(yourEvent.getPoint());
    for instance:
    myTable.addMouseListener(new MouseAdapter(){
    public void mousePressed(MouseEvent me){
    //there you get the row index
    int myIndex=myTable.rowAtPoint(me.getPoint());
    });

  • Listener for CheckBoxes in JTable

    Hi,
    I have a table that displays a checkbox in one of the fields. Which event handler/ listener should I use? Eg: Checkbox listener, List listener or otherwise?
    A change in the checkbox value (tick or untick) will trigger recalculation.
    Thanks.

    I can't really understand your problem.
    Here's a simple example that will print out the new check box state when you press the checkbox:
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableModel;
    public class TableCheckboxListenerExample {
        public static void main(String[] args) {
            try {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);
                DefaultTableModel model = new DefaultTableModel(new Object[][] {{Boolean.FALSE, "Row 1"}, {Boolean.TRUE, "Row 2"}}, new String[] {"col1", "col2"}) {
                    public Class<?> getColumnClass(int columnIndex) {
                        if (getRowCount() > 0 && getValueAt(0, columnIndex) != null)
                            return getValueAt(0, columnIndex).getClass();
                        return super.getColumnClass(columnIndex);
                model.addTableModelListener(new TableModelListener() {
                    public void tableChanged(TableModelEvent e) {
                        int row = e.getFirstRow();
                        int column = e.getColumn();
                        TableModel model = (TableModel)e.getSource();
                        Object data = model.getValueAt(row, column);
                        if (data instanceof Boolean)
                            System.out.println("Value changed in Row: " + row + " Column: " + column + " New Value = " + data);
                JTable table = new JTable(model);
                frame.add(new JScrollPane(table));
                frame.pack();
                frame.setVisible(true);
            catch (Exception e) {e.printStackTrace();}       
    }

  • Way to listen for change in JTable cell?

    I am having troubles trying to catch a key event while the user is entering text inside a given JTable cell (x/y location). The JTable only seems to manage String objects in it's cells so I can't place a JTextField in there with a KeyListener on it.
    Currently, I can only get control of the application once the user has left the cell they are editing.
    Does anyone have an example of a JTable 'cell KeyListener' scenario? At this point I want to see if I can print 'hello world' each time I type a character within a cell. Then I'll go from there....

    If you want to know when the contents of a cell have been updated you should use a TableModelListener.
    If you want to know when a character is added/removed from the cell editor then you need to first understand how this works with a simple text field.
    Typically you would use a DocumentListener to receive notifies of a change to the text field. However, within the DocumentEvent you wouldn't be able to change the text field as this notification comes after the text field has already been updated.
    If you need to ability to intercept changes to the text field before they happen, then you would need to use a DocumentFilter. An example of using a DocumentFilter is given in the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#filter]Text Component Features.
    Once you get your regular text field working the way you want, the next step to create a DefaultCellEditor using this JTextField and use this editor in your JTable. The above tutorial also has a section on using editors in a table.

  • How to listen for resizing of JTable column

    Is there anyway to tell when the columns in a JTable are being resized by the user? I couldn't find any listeners or anything that will tell you when the user is dragging the column width with the mouse.
    Thanks.

    Use ColumnModelListener as shown below:-
              table.getColumnModel().addColumnModelListener(new TableColumnModelListener() {
                   public void columnAdded(TableColumnModelEvent e) {
                   public void columnMoved(TableColumnModelEvent e) {
                   public void columnRemoved(TableColumnModelEvent e) {
                   public void columnMarginChanged(ChangeEvent e) {
                   public void columnSelectionChanged(ListSelectionEvent e) {
              });

  • Which listener should be used for JTextArea

    Hi,
    I need to add a listener for JTextArea particualy when
    the text in the jtextarea is changed. I don't think
    mouse listener is enough, since the user can use tab to
    get to the jtextarea and edit the text. In this case,
    which listener should I use. Sample code would be
    helpful.
    In addition, I have a problem with the jtextarea that
    when user uses tab to go to different gui components,
    such as jtextfield, jcombobox, jtextarea, jlist, etc, the
    tab stays in the jtextarea and keeps appending to it. It does
    not go to next component, such as jlist. How can I make it
    work?
    Thanks in advance,
    Pin

    It doesn't work. Are you using 1.4 or 1.3? I am using
    1.4.
    In the 1.4 API, it says that isManagingFocus is
    "Deprecated".
    Here is what I have:
    JTextArea descrptArea = new JTextArea() {
    public boolean isManagingFocus() {
    return false;
    descrptArea.setRows(3);
    descrptArea.setLineWrap(true);
    descrptArea.addKeyListener(new KeyAdapter() {
    public void keyTyped(KeyEvent e) {
    // DO SOMETHING
    I found the following code which says it will do it.
    However, I got the exeception:
    java.lang.ClassCastException:
    n: javax.swing.KeyStroke
    at java.util.TreeMap.compare(TreeMap.java:1081)
    at java.util.TreeMap.put(TreeMap.java:459)
    at java.util.TreeSet.add(TreeSet.java:205)
    Set forwardTraversalKeys = new TreeSet();
    forwardTraversalKeys.add(KeyStroke.getKeyStroke('\t'));
    forwardTraversalKeys.add(KeyStroke.getKeyStroke(KeyEven
    .VK_TAB,
    InputEvent.CTRL_MASK));
    textArea.setFocusTraversalKeys
    (KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
    forwardTraversalKeys);
    Set backwardTraversalKeys = new TreeSet();
    backwardTraversalKeys.add(KeyStroke.getKeyStroke(KeyEve
    t.VK_TAB,
    InputEvent.SHIFT_MASK));
    backwardTraversalKeys.add(KeyStroke.getKeyStroke(KeyEve
    t.VK_TAB,
    InputEvent.SHIFT_MASK |InputEvent.CTRL_MASK));
    textArea.setFocusTraversalKeys(
    KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
    backwardTraversalKeys);
    Any idea???
    PinI'm not using 1.4 but the class cast exceptions look like they come from : Set forwardTraversalKeys=new TreeSet() etc
    try : TreeSet forwardTraversalKeys=new TreeSet()
    you cant cast from a Set to a TreeSet because a TreeSet is a Set but a Set is NOT a TreeSet.
    hope this helps.

  • Listening for Changes to JTextArea

    I am writing a program that listens for changes to the contents of a JTextArea to obtain input for its execution. But I have implemented DocumentListener, PropertyChangeListener to listen for changes to the JTextArea for deriving input without success. Please could anyone advice on what to do.
    My code is below.
       myListener implements DocumentListener{
       JTextArea txt = new JTextArea();
       txt.getDocument().addDocumentListener(this);
       public void changedUpdate(DocumentEvent e){}
       public void removeUpdate(DocumentEvent e){} 
       public void insertUpdate(DocumentEvent e){
        try{
         //my code for obtaining input from txt is here
         int start = e.getOffset();
         Document doc = e.getDocument();
        }catch(BadLocationException ble){
    }

    Here's a link to the Swing tutorial on "How to Write a Document Listener":
    http://java.sun.com/docs/books/tutorial/uiswing/events/documentlistener.html

  • Multiple Buttons in JTable Headers:  Listening for Mouse Clicks

    I am writing a table which has table headers that contain multiple buttons. For the header cells, I am using a custom cell renderer which extends JPanel. A JLabel and JButtons are added to the JPanel.
    Unfortunately, the buttons do not do anything. (Clicking in the area of a button doesn't appear to have any effect; the button doesn't appear to be pressed.)
    Looking through the archives, I read a suggestion that the way to solve this problem is to listen for mouse clicks on the table header and then determine whether the mouse clicks fall in the area of the button. However, I cannot seem to get coordinates for the button that match the coordinates I see for mouse clicks.
    The coordinates for mouse clicks seem to be relative to the top left corner of the table header (which would match the specification for mouse listeners). I haven't figured out how to get corresponding coordinates for the button. The coordinates returned by JButton.getBounds() seem to be relative to the top left corner of the panel. I hoped I could just add those to the coordinates for the panel to get coordinates relative to the table header, but JPanel.getBounds() gives me negative numbers for x and y (?!?). JPanel.getLocation() gives me the same negative numbers. When I tried JPanel.getLocationOnScreen(), I get an IllegalComponentStateException:
    Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
    Can someone tell me how to get coordinates for the button on the JTableHeader? Or is there an easier way to do this (some way to make the buttons actually work so I can just use an ActionListener like I normally would)?
    Here is relevant code:
    public class MyTableHeaderRenderer extends JPanel implements TableCellRenderer {
    public MyTableHeaderRenderer() {
      setOpaque(true);
      // ... set colors...
      setBorder(UIManager.getBorder("TableHeader.cellBorder"));
      setLayout(new FlowLayout(FlowLayout.LEADING));
      setAlignmentY(Component.CENTER_ALIGNMENT);
    public Component getTableCellRendererComponent(JTable table,
                                                     Object value,
                                                     boolean isSelected,
                                                     boolean hasFocus,
                                                     int row,
                                                     int column){
      if (table != null){
        removeAll();
        String valueString = (value == null) ? "" : value.toString();
        add(new JLabel(valueString));
        Insets zeroInsets = new Insets(0, 0, 0, 0);
        final JButton sortAscendingButton = new JButton("1");
        sortAscendingButton.setMargin(zeroInsets);
        table.getTableHeader().addMouseListener(new MouseAdapter(){
          public void mouseClicked(MouseEvent e) {
            Rectangle buttonBounds = sortAscendingButton.getBounds();
            Rectangle panelBounds = MyTableHeaderRenderer.this.getBounds();
            System.out.println(Revising based on (" + panelBounds.x + ", "
                               + panelBounds.y + ")...");
            buttonBounds.translate(panelBounds.x, panelBounds.y);
            if (buttonBounds.contains(e.getX(), e.getY())){  // The click was on this button.
              System.out.println("Calling sortAscending...");
              ((MyTableModel) table.getModel()).sortAscending(column);
            else{
              System.out.println("(" + e.getX() + ", " + e.getY() + ") is not within "
                                 + sortAscendingButton.getBounds() + " [ revised to " + buttonBounds + "].");
        sortAscendingButton.setEnabled(true);
        add(sortAscendingButton);
        JButton button2 = new JButton("2");
        button2.setMargin(zeroInsets);
        add(button2);
        //etc
      return this;
    }

    I found a solution to this: It's the getHeaderRect method in class JTableHeader.
    table.getTableHeader().addMouseListener(new MouseAdapter(){
      public void mouseClicked(MouseEvent e) {
        Rectangle panelBounds = table.getTableHeader().getHeaderRect(column);
        Rectangle buttonBounds = sortAscendingButton.getBounds();
        buttonBounds.translate(panelBounds.x, panelBounds.y);
        if (buttonBounds.contains(e.getX(), e.getY()) && processedEvents.add(e)){  // The click was on this button.
          ((MyTableModel) table.getModel()).sortAscending(column);
    });

  • Mouse motion listener for JTable with JScrollpane

    Hi All,
    I have added mouse motion listener for JTable which is added in JScrollPane. But if i move the mouse, over the vertical/horizontal scroll bars, mouse motion listener doesn't works.
    So it it required to add mousemotionlistener for JTable, JScrollPane, JScrollBar and etc.
    Thanks in advance.
    Regards,
    Tamizhan

    I am having one popup window which shows address information. This window contains JTable with JScrollPane and JButton components to show the details. While showing this information window, if the mouse cursor is over popupwindow, it should show the window otherwise it should hide the window after 30 seconds.
    To achieve this, i have added mouse listener to JPanel, JTable, JButton and JScrollPane. so if the cursor is in any one of the component, it will not hide the window.
    but for this i need to add listener to all the components in the JPanel. For JScrollPane i have to add horizontal, vertical and all the top corner buttons of Scroll bar.
    Is this the only way to do this?

  • Listener for custom JTable

    I need to know when a user clicks in a certain column in a JTable. This column displays checkboxes. How do i implement a listener for this and where do i put it? I've tried implementing actionlistener with an editor class, but the event never fires.

    In the future, Swing related questions should be posted in the Swing forum.
    You need to add a TableModelListener to the TableModel. It will notify you when the value of a cell is changed.

  • How do I listen for changes in a container's components?

    I have a JScrollPane that contains a JTextPane. I want any Container that can possibly contain my JScrollPane to be able to listen for changes in the JTextPane's Document.
    For example, at the moment I'm using a JTabbedPane to hold a number of my JScrollPanes and I want to alter the tab title when any associated JScrollPane-JTextPane-Document is updated.
    Any suggestions on how best to handle this?

    I would use a controller object that manages all your gui components (tabs, scrolls, documents, text panes). Your controller object can register as a listener to the appropriate component, and when it changes, update the title of a tab (or do whatever else) as appropriate.
    Never put business logic like this stuff inside the actual gui components. Create, layout, etc. all the gui components (and related components like Document) from another controller like object instead. It makes handling the various listener stuff like this much easier. Read up on MVC (model view controller) stuff for more info.
    As for the actual mechanics, you could get the document that is used in the JTextPane and register as a DocumentListener. As a document listener, you get notified of all changes that are made to that document.

  • Customize "Tab" key for JTextArea to focus next component.

    Hi,
    I am trying to change the "TAB" key behaviour for JTextArea, by using CustomAction configured via InputMap() and ActionMap(). When the user presses the Tab key, the focus should go the next component instead of tabbing in the same JTextArea component. Here is the code for the CustomAction().
        public static class CustomTabAction extends AbstractAction {
            private JComponent comp;
            public CustomTabAction (JComponent comp) {
                this.comp = comp;
                this.comp.getInputMap().put(KeyStroke.getKeyStroke("TAB"), "TABPressed");
                this.comp.getActionMap().put("TABPressed", this);
            public void actionPerformed(ActionEvent evt) {
                Object source = evt.getSource();
                if (source instanceof Component) {
                    FocusManager.getCurrentKeyboardFocusManager().
                            focusNextComponent((Component) source);
        }This works for most of the cases in my applicaiton. The problem is that it doesn't work with JTable which has a custom cell editor (JTextArea). In JTextArea field of JTable, if the Tab is pressed, nothing happens and the cursor remains in the custom JTextArea exactly at the same place, without even tabbing spaces. Here is the CustomCellEditor code.
        public class DescColCellEditor extends AbstractCellEditor implements TableCellEditor {
    //prepare the component.
            JComponent comp = new JTextArea();
            public Component getTableCellEditorComponent(JTable table, Object value,
                    boolean isSelected, int rowIndex, int vColIndex) {
                // Configure Tab key to focus to next component
                CustomActions.setCustomAction("CustomTabAction", comp);
                // Configure the component with the specified value
                ((JTextArea)comp).setText((String)value);
                // Return the configured component
                return comp;
            // This method is called when editing is completed.
            // It must return the new value to be stored in the cell.
            public Object getCellEditorValue() {
                return ((JTextArea)comp).getText();
        }regards,
    nirvan

    >
    textArea.getInputMap().remove(....);but that won't work because the binding is actually defined in the parent InputMap. So I think you need to use code like:
    textArea.getInputMap().getParent().remove(...);But I'm not sure about this as I've never tried it.I tried removing the VK_TAB key from both the input map and parent input map as shown below. But I still have to press "TAB" twice in order to get out of the JTextArea column in JTable.
                comp.getInputMap().getParent().remove(
                            KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0));
                comp.getInputMap().remove(
                            KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0));after coding this, I am using the setFocusTraversalKeys for adding only "TAB" key as ForwardTraversalKey as given below.
            Set newForwardKeys = new HashSet();
            newForwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));
            comp.setFocusTraversalKeys(
                        KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,newForwardKeys);
            Set newBackwardKeys = new HashSet();
            newBackwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, KeyEvent.SHIFT_DOWN_MASK));
            comp.setFocusTraversalKeys(
                        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,newBackwardKeys);The only problem that remains now is that I have to press the "TAB" twice in order to get out of the JTextArea column
    regards,
    nirvan.

  • JTextfield  listening for changes from other class

    Hi,
    Assuming I have a Jtextfield in one of the class1 extend Jframe,
    how do I update the jtextfield so that it could up make accessible by other class and continuously updated to reflect the input for value rom another class2.
    In other words very much similar to the observable model view concept
    class 1 may be look like
    private void initComponents() {
    jTextField1 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jTextField1.setEditable(false);
    class 2 may be look similar to the following
    public void out_1(){
    setStop1("N");
    for (int i=1;i<100;i++){
    class_1.getJTextField1().setText(String.valueOf(i)); // System.out.println(i);
    setOuti(i);
    setStop1("N");

    HI,
    I have attempted with the following coding , test 1 the source display generated using Netbeans GUI , t est2 the worker code ,and mybean the bean , so far nothing seems to work .
    I have not try the threaded swing concept as I am not familar with the concurrency but i am not sure whether propertylistener will do the job or not
    In summary , list of method employed are :
    binding the jtextfield1 to a bean,
    jtextfield add document listener ,
    Coding objective
    1. Test 1 defined jtexfield1 and jbutton
    2 Jbutton added actionlistener , where upon click,
    Execute Test 2 which will assign a series of integer to the bean , own setters & getters, Output is achieved via Test 1 jtextfield1 supposingly to display all the running number from 1 to 99 continuously until the test2 out_1 method finished the execution
    Anyone could provide the assistance .
    Thank
    * Test_1.java
    * Created on July 25, 2007, 9:23 PM
    package sapcopa;
    import java.beans.PropertyChangeListener;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.text.Document;
    import sapcopa.MyBean.*;
    public class Test_1 extends javax.swing.JFrame {
    /** Creates new form Test_1 */
    // private Test_2 t2=new Test_2();
    private String input_txt;
    public Test_1() {
    myBean1=new MyBean();
    myBean1.addPropertyChangeListener(new java.beans.PropertyChangeListener(){
    public void propertyChange(java.beans.PropertyChangeEvent evt) {
    bean_chg(evt);
    initComponents();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
    myBean1 = new sapcopa.MyBean();
    jTextField1 = new javax.swing.JTextField();
    jTextField1.getDocument().addDocumentListener(new MyDocumentListener());
    jButton1 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jTextField1.setEditable(false);
    jTextField1.setText(myBean1.getRecord_Process());
    jTextField1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
    public void propertyChange(java.beans.PropertyChangeEvent evt) {
    txt1_chg(evt);
    jButton1.setText("jButton1");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    But1(evt);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(19, 19, 19)
    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(layout.createSequentialGroup()
    .addGap(32, 32, 32)
    .addComponent(jButton1)))
    .addContainerGap(131, Short.MAX_VALUE))
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGap(21, 21, 21)
    .addComponent(jButton1)
    .addContainerGap(216, Short.MAX_VALUE))
    pack();
    }// </editor-fold>//GEN-END:initComponents
    private void txt1_chg(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_txt1_chg
    // TODO add your handling code here:
    //myBean1=new MyBean();
    try {
    jTextField1.setText(myBean1.getRecord_Process());
    } catch (Exception e){
    e.printStackTrace();
    }//GEN-LAST:event_txt1_chg
    private void bean_chg(java.beans.PropertyChangeEvent evt){
    jTextField1.setText(myBean1.getRecord_Process());
    private void But1(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_But1
    //getJTextField1().getDocument().addDocumentListener(new MyDocumentListener());
    Test_2 t2=new Test_2();
    t2.out_1();
    try{
    System.out.println("Button 1 mybean->"+myBean1.getRecord_Process());
    } catch (Exception e){
    e.printStackTrace();
    // TODO add your handling code here:
    }//GEN-LAST:event_But1
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Test_1().setVisible(true);
    public javax.swing.JTextField getJTextField1() {
    return jTextField1;
    public void setJTextField1(javax.swing.JTextField jTextField1) {
    this.jTextField1 = jTextField1;
    class MyDocumentListener implements DocumentListener {
    final String newline = "\n";
    public void insertUpdate(DocumentEvent e) {
    // updateLog(e, "inserted into");
    String vstr=myBean1.getRecord_Process().toString();
    jTextField1.setText(vstr);
    public void removeUpdate(DocumentEvent e) {
    //updateLog(e, "removed from");
    String vstr=myBean1.getRecord_Process().toString();
    jTextField1.setText(vstr);
    public void changedUpdate(DocumentEvent e) {
    //Plain text components don't fire these events.
    String vstr=myBean1.getRecord_Process().toString();
    jTextField1.setText(vstr);
    public void updateLog(DocumentEvent e, String action) {
    Document doc = (Document)e.getDocument();
    int changeLength = e.getLength();
    // jTextField1.setText(String.valueOf(changeLength));
    String vstr=myBean1.getRecord_Process().toString();
    jTextField1.setText(vstr);
    public String getInput_txt() {
    return input_txt;
    public void setInput_txt(String input_txt) {
    this.input_txt = input_txt;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JTextField jTextField1;
    private sapcopa.MyBean myBean1;
    // End of variables declaration//GEN-END:variables
    * Test_2.java
    * Created on July 25, 2007, 9:26 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package sapcopa;
    import sapcopa.MyBean.*;
    public class Test_2 {
    private Test_1 t1=new Test_1();
    private int outi;
    private String stop1;
    MyBean mybean;
    /** Creates a new instance of Test_2 */
    public Test_2() {
    public void out_1(){
    setStop1("N");
    mybean=new MyBean();
    for (int i=1;i<100;i++){
    mybean.setRecord_Process(String.valueOf(i));
    setOuti(i);
    setStop1("N");
    setStop1("Y");
    public int getOuti() {
    return outi;
    public void setOuti(int outi) {
    this.outi = outi;
    public String getStop1() {
    return stop1;
    public void setStop1(String stop1) {
    this.stop1 = stop1;
    * MyBean.java
    * Created on July 24, 2007, 12:00 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package sapcopa;
    import javax.swing.JTextField;
    public class MyBean {
    /** Creates a new instance of MyBean */
    public MyBean() {
    * Holds value of property record_Process.
    private JTextField txt_rec_process;
    private String record_Process;
    * Utility field used by bound properties.
    private java.beans.PropertyChangeSupport propertyChangeSupport = new java.beans.PropertyChangeSupport(this);
    * Adds a PropertyChangeListener to the listener list.
    * @param l The listener to add.
    public void addPropertyChangeListener(java.beans.PropertyChangeListener l) {
    propertyChangeSupport.addPropertyChangeListener(l);
    * Removes a PropertyChangeListener from the listener list.
    * @param l The listener to remove.
    public void removePropertyChangeListener(java.beans.PropertyChangeListener l) {
    propertyChangeSupport.removePropertyChangeListener(l);
    * Getter for property record_Process.
    * @return Value of property record_Process.
    public String getRecord_Process() {
    return this.record_Process;
    * Setter for property record_Process.
    * @param record_Process New value of property record_Process.
    public void setRecord_Process(String record_Process) {
    String oldRecord_Process = this.record_Process;
    this.record_Process = record_Process;
    propertyChangeSupport.firePropertyChange("record_Process", oldRecord_Process, record_Process);
    * Holds value of property rec_Match.
    private String rec_Match;
    * Getter for property rec_Match.
    * @return Value of property rec_Match.
    public String getRec_Match() {
    return this.rec_Match;
    * Setter for property rec_Match.
    * @param rec_Match New value of property rec_Match.
    public void setRec_Match(String rec_Match) {
    String oldRec_Match = this.rec_Match;
    this.rec_Match = rec_Match;
    propertyChangeSupport.firePropertyChange("rec_Match", oldRec_Match, rec_Match);
    public JTextField getTxt_rec_process() {
    return txt_rec_process;
    public void setTxt_rec_process(JTextField txt_rec_process) {
    JTextField oldTxt_rec_process=this.txt_rec_process;
    this.txt_rec_process = txt_rec_process;
    propertyChangeSupport.firePropertyChange("txt_rec_process", oldTxt_rec_process, txt_rec_process);
    }

  • Listening for UncaughtErrorEvents from SubApp loaded by SWFLoader

    I can't seem to get my uncaughtErrorEvents listener to fire when attached to the loader.uncaughtErrorEvents  or loaded content's loaderInfo.uncaughtErrorEvents when loading a swf via SWFLoader.
    I have a main Flex Application ('A.swf') loading a SubApplication  (defined in' B.swf') via a SWFLoader and I need to listen for  UncaughtErrorEvent from the SubApplication. I'm not able to get my event  listeners to be called when I throw an error from within the SubApp  ('B.swf').
    After reading the asDoc for UncaughtErrorEvent and  UncaughtErrorEvents It states that the UncaughtErrorEvent should go through the normal capture, target, and bubble phases through the loaderInfo hierarchy. This doesn't seem to be the case or I'm not understanding the documentation/usage.
    I have added an event listener to A.swf's loaderInfo  (The 'outter' main app) and also to B.swf's loaderInfo (though the Docs  say not to do it here it is part of the event sequence in the capture  and bubble phase...) as well as the SWFLoader internal  FlexLoader.uncaughtErrorEvent (per Docs) like so:
    SWFLoader's internal FlexLoader uncaughtErrorEvents
    swfLoader.content.loaderInfo.loader.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorFunction );
    and the loaded SWF's loaderInfo:
    swfLoader.content.loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorFunction );
    When I throw an Error from the SubApplication (B.swf). Only the 'outter' main app's (A.swf) event listener gets called. Which you expect, at first, if it is in the capture phase, but it isn't in that eventPhase at all. When debugging the eventPhase is in the EventPhase.AT_TARGET phase while being handled by A.swf's LoaderInfo, howeever the ASDoc says the Target phase should be B.swf's LoaderInfo.
    Is this a bug between Flash player and Flex where the event isn't flowing correctly as stated in the ASDoc for UncaughtErrorEvent?

    Thanks for the reply Alex.
    The Outer main swf and the SubApp swf are in different ApplicationDomains (sibilings to each other) so they should not be sharing the class that is throwing the error. I should note that these two Applications are purely based on MX components, this is important later on.
    I was originally throwing the error from a Button click handler from B.swf:
    <mx:Button label="Throw Error" click="callLater( throwUncaughtError )" />
    I was wrapping the handler function in a callLater because without it the error is not caught at all and the default flash dialog console just appears with the error. The A.swf's loaderInfo.uncaughtErrorEvents handler was not even firing unless I wrapped it a callLater.
    I realized that Flash Builder's default to link the 4.1 SDK library via Runtime shared libraries was what was causing the A.swf's loaderInfo.uncaughtErrorEvent to fire in the AT_TARGET phase when using callLater. This is because the UIComponent's callLater method queue structure is shared between the two SWFs and therefore inside a function executing off the method queue A.swf's loaderInfo IS the TARGET... explainable, but at first thought that isn't how I'd expect this to work.
    I then decided to test this out by setting the SDK library to merge into the code for both A.swf and B.swf and removing the  callLater. IT WORKS!  B.swf's (the SubApp) loaderInfo.uncaughtErrorEvents handler fires and I prevent the default (flash error console from appearing) and can stopImmediatePropagation so A.swf's loaderInfo.uncaughtErrorEvents handler doesn't fire.
    Perfect besides having to merge the SDK libraries into each swf independently.... size killer.
    In summary, using the same exact code for A.swf and B.swf:
    1. When the SDK libraries are RSL - no UncaughtErrorEvents, neither A.swf's or B.swf's, is called. Instead the default flash error console appears with no chance to handle the uncaught error.
    2. When the SDK libraries are Merged into the code - both A.swf's and B.swf's uncaughtErrorEvents  will be called, according to the asDoc documented sequence; B.swf's uncaughtErrorEvents in the AT_TARGET phase and A.swf's uncaughtErrorEvents in the BUBBLE phase.
    Moreover, if I build a pure Spark implementation everything works even when referencing the SDK libraries as RSL.
    Does this indicate a bug in the globalplayer (flash player code)'s logic for handling UncaughtErrorEvents listeners within the loaderInfo hierarchy when the Flex SDK is Shared code between the SWFs?
    OR
    Since it works in Spark, is it an issue with how the flex2.compiler.mxml.Compiler turns MX based mxml components into generated AS classes (it hooks up the inline event listeners of child UIComponentDescriptor using a generic object and the click function is specified as a STRING and has to use untyped bracket notation to lookup on the UICompoent when adding it as a listener:
    new mx.core.UIComponentDescriptor({
                  type: mx.controls.Button
                  events: {
                    click: "___B_Button1_click"
                  propertiesFactory: function():Object { return {
                    label: "Throw Error"
    Where as Spark does this correctly and generates Factory functions for setting up child UIComponents when converting Spark component mxml to AS:
    private function _B_Button1_c() : spark.components.Button
        var temp : spark.components.Button = new spark.components.Button();
        temp.label = "Throw Error";
       temp.addEventListener("click", ___B_Button1_click);
        if (!temp.document) temp.document = this;
        mx.binding.BindingManager.executeBindings(this, "temp", temp);
        return temp;
    * @private
    public function ___B_Button1_click(event:flash.events.MouseEvent):void
        throwUncaughtError()
    Sadly, moving to pure Spark would be a big hit is my project's schedule and at this point and likely isn't feasible. I have examples (with view source) built in MX for both the RSL and MERGE cases, I just don't know how to attach them here.
    Sorry for the long comments and thanks again!

Maybe you are looking for

  • Need help-Error Message in HP Deskjet F4288 All-in-One

    Please help why I am getting an 'E' in the 'Start Copy' Panel. The Power/Start button light is on and it is not blinking. The Colour Cartridge has red blinking light though it is almost full. The moment I switch on my Printer, I get 'E' and red blink

  • Max number of pages in a spool

    Hi Gurus, I have a background job which takes an input file from app server.Input file has 50000 records.I need to process them inside the program and display the result in spool.Now,my question is ,will I be able to see all the records.is there any

  • Upgrade from 4.7 to ECC 6.0 - Purchase Order Statiscal Delivery Date

    Hi. I need your help please. When an order is created via ME21N, the Statistical Delivery date on the Delivery Schedule Tab gets populated automatically with the delivery date that was captured on the Item Detail, if not manually updated.This is how

  • Safari Quits When Trying to Send an Email With Attachments

    I use gmail to send attachments. Now whenever i try to send an message that has an attachment, it quits unexpectedly. This is the only problem i have with Safari. I created another account to check if the problem is in the account itself but Safari d

  • Plant & Profit Centre Combination

    Hi Friends. Is there any requirement that there should be 1:1 combination between Plant and Profit centre to derive the profit centre wise financial statements? Viz., I have 4 profit centers, have only one Plant and most of the materials are commonly