How to listen a JTable cell is changed?

is it have any Listener can know the JTable cell cursor change to other?
Thanks!

JTable exposes a ListSelectionModel through getSelectionModel() that you can listen to for changes in the selected row. I think you need to get the TableColumnModel to detect changes in the selected column:
table.getSelectionModel().addSelectionListener(selectionListener);
table.getColumnModel().getSelectionModel().addSelectionListener(selectionListener);selectionListener should get notified if a change is made to the selected row or column.
Hope this helps.

Similar Messages

  • PLEASE HELP-JTable cell editor-change one cell, changes all cells of column

    for example i have 3 rows 4 columns, column 3 and 4 are dates. now if i change the date to a new value (eg for of column 3)
    for any row, and then i click on any other cell. All cell values ie all rows for that column are changed to that new value.
    ie it changed column 3 for all rows 1, 2 and 3 to that new value which i changed in only one cell of that column.
    PLEASE HELP me , tell me what change i make to the code to fix it ....
    this is my cell renderer for date
    class DateCellRenderer extends JbcDateTimeChooser implements TableCellRenderer {
      protected Border m_noFocusBorder;
      public DateCellRenderer() {
        super();
        setStylePattern(JbcDateTimeChooser.MEDIUM);
        m_noFocusBorder = new EmptyBorder(1, 2, 1, 2);
        setOpaque(true);
        setBorder(m_noFocusBorder);
      public Component getTableCellRendererComponent(JTable table,
       Object value, boolean isSelected, boolean hasFocus,
       int row, int column)
      if(value instanceof Date) {
          Date b = (Date)value;
          setDate(b);
        setFont(table.getFont());
        setBorder(hasFocus ? UIManager.getBorder(
          "Table.focusCellHighlightBorder") : m_noFocusBorder);
        return this;
    }I have this custom cell editor date
    class DateCellEditor extends AbstractCellEditor implements TableCellEditor {
      protected JbcDateTimeChooser editor;
      public DateCellEditor() {
        super();
        editor = new JbcDateTimeChooser();
        editor.setStylePattern(JbcDateTimeChooser.MEDIUM);
      public Object getCellEditorValue() {
        return editor.getDate();
      public Component getTableCellEditorComponent(JTable table,
       Object value, boolean isSelected, int row, int column)
        if(value instanceof Date) {
          editor.setDate((Date)value);
        return editor;
    }and this is how i defined in jtable
        lnnTableModel = new CellSiteLNNTableModel();
        lnnTable.setModel(lnnTableModel);
        lnnTableModel.addColumn("ABC");
        lnnTableModel.addColumn("DEF");
        lnnTableModel.addColumn("Date From");
        lnnTableModel.addColumn("Date To");
        for(int k = 0; k < lnnTableModel.getColumnCount(); k++) {
          TableColumn col = lnnTable.getColumn(lnnTableModel.getColumnName(k));
          TableCellRenderer renderer;
            DefaultTableCellRenderer textRenderer = new DefaultTableCellRenderer();
            renderer = textRenderer;
          TableCellEditor editor;
          JTextField textColumn = new JTextField();
          if((k == CellSiteLNN.DATE_FROM) || (k == CellSiteLNN.DATE_TO)) {
            editor = new DateCellEditor();  //  this is the cell editor
         renderer = new DateCellRenderer(); // this is the assigned cell renderer
          } else {
            editor = new DefaultCellEditor(textColumn);
          col.setCellRenderer(renderer);
          col.setCellEditor(editor);
        }

    table model is extended from AbstractTableModel
    and have these methods
    do you see anything wrong here.....
      public Object getValueAt(int row, int column) {
        Vector rowVector = (Vector)dataVector.elementAt(row);
        return rowVector.elementAt(column);
      public void setValueAt(Object aValue, int row, int column) {
        Vector rowVector = (Vector)dataVector.elementAt(row);
        rowVector.setElementAt(aValue, column);
        // generate notification
        fireTableChanged(new TableModelEvent(this, row, row, column));
      } // end method (setValueAt)

  • JTable Cell Focus Change

    Hi all,
    Is it possible to keep track the cell focus change in JTable so that I can perform appropriate validation. For example, user use the key to move from cell (2,3) to (2,4) or use the mouse to move from (2,4) to (5,3).
    I know that it is possible to use ListSelectionEvent on SelectionModel (for row change) and & ColumnModel (for change change) to do that. However, when both row & column change simultaneously, I need to do only 1 validation (in fact, the validation must have both information). My existing code gives me two separate event instead.
    Any idea ? Thanks in advance.

    This will be a decently hard nut to crack without making a slightly (or worse) cluttered solution.
    I've been part of a framework where applications-developer has requested solutions like you currently ask for. The solution we implemented was twofold.
    1) We made an centralised TableModel that people could use as-is or extend if nessecary. To this tablemodel we added a new set of events that could be consumed, or in some cases even replaced.
    The events was for instance 'beforeCellChange' and contained enough data on the current value, the new value, location in model and space for replacing any of the above values. Many more events was added as time went by as well.
    We made the event-listener fairly generalized and the type sent in the actual event, this allowed us to expand the events without having to change any interfaces. The drawback with this was that it forces the developer to check which type of event is happening, a bit like events happened in AWT 1.0.
    With the help of this, the developers just added the nessecary listeners to the table model and they could consume, change, validate any input to a table before it was committed.
    2) No good method for row-verification could really be found.
    There was a few futile tries, but since data could be entered in any order, the validation raised the amount of code with a order of magnitude. It does work, by listening on selection events, but quite a few extra checks has to be resolved, as instance with rows not validated etc etc.
    My recomendations, verify data carefully from events either from model or the table-editor. The result will most assurdly end in that you need to have an tablemodel on your own and also TableCellRenderer to accomplish all that you want to do.
    Yours sincerely
    Peter Norell

  • Listen for excel cell data change

    I want to develop a program that listens when an excel cell value changes...

    snoopybad77 wrote:
    I use http://jdde.pretty-tools.com/ very simple but working.
    By the looks of it, you might want to start with [DDEClientEventListener.onItemChanged()|http://jdde.pretty-tools.com/javadoc/com/pretty_tools/dde/client/DDEClientEventListener.html#onItemChanged%28java.lang.String,%20java.lang.String,%20java.lang.String%29], but I've got absolutely no idea how it works, never having used the product before.
    Winston
    Edited by: YoungWinston on Jul 5, 2010 1:43 AM
    PS: It looks like there's something very similar to what you want on their examples page as well. You clearly haven't done much looking.

  • How to listener a table cell

    I have this table cell editable and I want to listen when value changes (to update the database data) but I am not being able to do that, any help?
    I also would like to activate the new cell value with ENTER key, the way it is now I have to get ou of the cell clicking outside somewhere or using TAB key to move.
    I am using these tow classes to Editor and Renderer (for numbers):
    import java.awt.*;
    import java.text.*;
    import javax.swing.table.*;
    import javax.swing.*;
    public class DecimalRenderer extends DefaultTableCellRenderer {
        DecimalFormat  formatter;
        public DecimalRenderer(String pattern) {
            this(new DecimalFormat(pattern));
        public DecimalRenderer(DecimalFormat formatter) {
            this.formatter = formatter;
            setHorizontalAlignment(JLabel.RIGHT);
        public void setValue(Object value) {
            setText((value == null) ? "" : formatter.format(((Double)value).doubleValue()));
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            cell.setBackground( Color.white );
            cell.setForeground( Color.black );
            return cell;
    import java.awt.*;
    import javax.swing.table.*;
    import javax.swing.*;
    public class NumberCellEditor extends AbstractCellEditor implements TableCellEditor {
        //protected JTextField textField;
        protected JFormattedTextField textField;
        private JTable tableUsed;
        protected Object oldValue;
        public NumberCellEditor() {
            textField = new JFormattedTextField();
            textField.setEditable(true);
            textField.setHorizontalAlignment(SwingConstants.RIGHT);
            textField.setFont(new java.awt.Font("Tahoma", 1, 12));
            textField.setBackground(Color.white);
            textField.setForeground(Color.red);
        public NumberCellEditor(int decimal) {
            textField = new JFormattedTextField();
            textField.setEditable(true);
            textField.setHorizontalAlignment(SwingConstants.RIGHT);
            textField.setBackground(Color.white);
            textField.setForeground(Color.red);
            textField.setFormatterFactory(Lib.setFormatDouble(decimal));
            public NumberCellEditor(boolean currency, int decimal) {
            textField = new JFormattedTextField();
            textField.setEditable(true);
            textField.setHorizontalAlignment(SwingConstants.RIGHT);
            textField.setBackground(Color.white);
            textField.setForeground(Color.red);
            textField.setFormatterFactory(Lib.setCurrencyFormat(decimal));
        private void setConfig(){
            textField.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    if(tableUsed.isEditing()){
                        tableUsed.getCellEditor().stopCellEditing();
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            //textField.setText(value.toString());
            textField.setValue(value);
            oldValue = value;
            this.tableUsed = table;
            String className = value.getClass().getName();
            System.out.println("Type: "+className);
            return textField;
        /** Returns the value contained in the editor */
        public Object getCellEditorValue() {
            String name = oldValue.getClass().getName();
            Object returnValue=null;
            try {
                if (name.equals("java.lang.Integer"))
                    returnValue = new java.lang.Integer(textField.getText());
                else if (name.equals("java.lang.Double"))
                    returnValue = (Double)textField.getValue(); //new java.lang.Double(textField.getText());
                else if (name.equals("java.lang.Float"))
                    returnValue = new java.lang.Float(textField.getText());
                else if (name.equals("java.lang.Long"))
                    returnValue = new java.lang.Long(textField.getText());
                else if (name.equals("java.lang.Short"))
                    returnValue = new java.lang.Short(textField.getText());
                else if (name.equals("java.lang.Byte"))
                    returnValue = new java.lang.Byte(textField.getText());
                else if (name.equals("java.math.BigDecimal"))
                    returnValue = new java.math.BigDecimal(textField.getText());
                else if (name.equals("java.math.BigInteger"))
                    returnValue = new java.math.BigInteger(textField.getText());
            } catch (NumberFormatException e) {}
            return returnValue;
    }My code to that column/cell:
    TableColumn columnValueService = tabelaListaQuantidade.getColumn(colunas[4]);
    columnValueService.setPreferredWidth(150);
    columnValueService.setCellRenderer(new DecimalRenderer("###,###,##0.00"));
    columnValueService.setCellEditor(new NumberCellEditor(true, 2));I would appreciate any help.
    Thanks

    I want to listen when value changes Use a TableModelListener
    I also would like to activate the new cell value with ENTER keyThis is the default behaviour with the default editors. I suggest you extend the default editor instead of extending the abstract editor

  • How to make the jtable celles intouchable !!

    HI!
    i am using jtable in my application and i am aiming at some specefities:
    - i don't wana to allow the uset to drag and drop any cells or to change the order of one cell by another .
    - i don't want him to edit a text in any cell of the jtable
    actually, to resume everything, i want the jtable to be static one, and not changeable .
    any help will be really appreciated.
    thanks

    try importing javax.swing.JTable.*;
    there must be another class in javax.swing.*; that also has a getTableHeader() or setReorderingAllowed() method and the compiler is not sure which method to use. When in doubt, always import the specific class you want to use. Example:
    TestTable tt = new javax.swing.JTable(); // no confusion with this
    // declaration.
    At least, I think that should solve your problem. When you import a general library (like swing), there's always the possibility of using methods or fields that can belong to more than one class. Let me know if that works.
    James

  • A Listener For JTable Row Selection Changed?

    Never mind... Thought of a couple other things after I posted and found ListSelectionListener. This looks like it fulfills my requirement nicely. - cimmerian76
    >>>
    TableModelListener isn't what I am looking for here. Basically, I'm looking for something that behaves in a way that is analogous to
    TreeSelectionListener's valueChanged(...). Perhaps I'm looking in the wrong places, but the only things I've found were RowSet listener (not even close)
    and TableModelListener (not exactly what I'm looking for - I'm not concerned about data in the table changing).
    The tool I'm writing displays additional information about the object in the row selected in an adjacent panel.
    This display should change every time a user selects a different row.
    I can mimic the behavior I want using a mouse listener on the table, so this isn't an emergency.
    It's more about curiosity. If I can find something that produces this functionality directly, I would prefer to use that.
    <<<
    Message was edited by:
    cimmerian76

    Hi,
    you can use this to handle selection events for the table:
    yourTable.getSelectionModel().addListSelectionListener(... );
    Now e.g. the class containing your main can implement interface ListSelectionListener.

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

  • JTable Cell Change Listener

    I have a JTable which contains all the services charges and It should automatically calculate the Total of all the service Charges and so my client wants that on JTable Cell Change the total field should be updated
    So Can any body give me the event listener for that
    Thanks in advance
    CSJakharia

    Thanks for that
    That Works But do u know anything which prevents the continous loop
    I mean I have to change certain fields in the JTable itself in the listner itself and if i do that it ends up in Stack Overflow Exception Which implies never ending loop
    I can stop that with the use of variable But is there any easy way out I mean any method by which i can stop this endless LOOP

  • How to catch the mouse event from the JTable cell of  the DefaultCellEditor

    Hi, my problem is:
    I have a JTable with the cells of DefaultCellEditor(JComboBox) and added the mouse listener to JTable. I can catch the mouse event from any editor cell when this cell didn't be focused. However, when I click the editor to select one JComboBox element, all the mouse events were intercepted by the editor.
    So, how can I catch the mouse event in this case? In other word, even if I do the operation over the editor, I also need to catch the cursor position.
    Any idea will be highly appreciated!
    Thanks in advance!

    Hi, bbritta,
    Thanks very much for your help. Really, your code could run well, but my case is to catch the JComboBox event. So, when I change the JTextField as JComboBox, it still fail to catch the event. The following is my code. Could you give me any other suggestion?
    Also, any one has a good idea for my problem? I look forward to the right solution to this problem.
    Thanks.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test3
    extends JFrame {
    // JTextField jtf = new JTextField();
    Object[] as = {"aa","bb","cc","dd"};
    JComboBox box = new JComboBox(as);
    public Test3() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = getContentPane();
    String[] head = {
    "One", "Two", "Three"};
    String[][] data = {
    "R1-C1", "R1-C2", "R1-C3"}
    "R2-C1", "R2-C2", "R2-C3"}
    JTable jt = new JTable(data, head);
    box.addMouseListener(new MouseAdapter() {
    // jtf.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e)
    System.out.println("-------------------JComboBox mouseclick....");
    jt.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e)
    System.out.println("-------------------JTable mouseclick....");
    // jt.setDefaultEditor(Object.class, new DefaultCellEditor(jtf));
    jt.setDefaultEditor(Object.class, new DefaultCellEditor(box));
    content.add(new JScrollPane(jt), BorderLayout.CENTER);
    setSize(300, 300);
    public static void main(String[] args) {
    new Test3().setVisible(true);
    }

  • How to write an element in a  JTable Cell

    Probably it's a stupid question but I have this problem:
    I have a the necessity to build a JTable in which, when I edit a cell and I push a keyboard button, a new Frame opens to edit the content of the cell.
    But the problem is how to write something in the JTable cell, before setting its model. Because, I know, setCellAT() method of JTree inserts the value in the model and not in the table view. And repainting doesn't function!
    What to do??
    Thanks

    Hi there
    Depending on your table model you should normally change the "cell value" of the tablemodel.
    This could look like:
    JTable table = new JTable();
    TableModel model = table.getModel();
    int rowIndex = 0, columnIndex = 0;
    model.setValueAt("This is a test", rowIndex, columnIndex);
    The tablemodel should then fire an event to the view (i.e. JTable) and the table should be updated.
    Hope this helps you

  • How to paint a Custom Cell  while you are editing on adjacent Cell in JTabl

    Hi All,
    I have two Columns in my Custom Table . Both Two Columns are Custom Cell Editors/Renderers.
    I have made UI such that Column1 is Label , Column 2 is TextBox / Combo/ UI Input any
    My Custom Table View when i edit some value against Max Conn. it should display Blue
    =================================
    Column A | Column B
    ==================================
    Timeout | some_unchanged_value
    *{color:#0000ff}Session{color}* | some_unchanged_value
    Log File | some_unchanged_value
    ===================================
    My issue is when i start typing in my Custom Editor suppose i Type /invoke Edtir of Index 2, Column 2 font should become Blue.
    It becomes blue only when i debug this issue it perfectly works, without Debugger it doesnt changes the Font
    MyDefaultRenderer is my Custom renderer - I have set Foregroud Color as BLUE
    NOTE:_
    In run method if table.repaint() instead of single renderer:
    It turns Blue when i make call on table.repaint() methosd but i feel that repainting full table on every key Stroke should not be very good programming. Whats is more appropriate way?
    I want to repaint only that particular cell against which i change the Value
        private class MyDefaultEditor extends AbstractCellEditor implements TableCellEditor {
            private JTextField txtField = null;
            private int rowIndex;
            public MyDefaultEditor() {
                txtField = new JTextField();
                txtField.addKeyListener(new KeyAdapter() {
                    @Override
                    public void keyTyped(KeyEvent e) {
                        super.keyTyped(e);
                        System.out.println("########### Hello This is MyDefaultEditor");
                  SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                  // Call Renderer adjacentt to input to turn Blue (Is this Valid Code ??)
                                MyDefaultRenderer defRen = (MyDefaultRenderer) thisTable.getCellRenderer(activeRowIndex, 0);
                                defRen.paintMe();
              // table.repaint() works for me but i dont want to call it on evey ket type, that will be Heave rite???
            public Component getTableCellEditorComponent(JTable table,
                    Object value, boolean isSelected, int row, int column) {
                rowIndex = row;
                String valStr = "";
                if (value != null && value instanceof String) {
                    valStr = value.toString();
                txtField.repaint();
                return txtField;
            public Object getCellEditorValue() {
                return txtField.getText();
        }Edited by: Shubhadeep on Jun 27, 2009 1:58 AM
    Edited by: Shubhadeep on Jun 27, 2009 2:01 AM
    Edited by: Shubhadeep on Jun 27, 2009 2:06 AM
    Edited by: Shubhadeep on Jun 27, 2009 2:12 AM

    Well, I think you need to add a custom renderer to the first column. The renderer would check if the table.isEditing(). If it is and the editing is done on the same row, then you set the font color blue, otherwise you use the default font color.
    Then the next question is how do you repaint the cell. Well you can use the table.repaint(Rectangle) method. You can get the Rectangle to repaint by using the table.getCellRect(...) method.
    Finally, you need to know when to repaint the cell. Well a PropertyChangeEvent is fired when a cell starts and stops editing. So you only need to handle these events. Don't use a KeyListener. The PropertyChangeListener you add to the table might be something like:
    public void propertyChange(PropertyChangeEvent e)
         if ("tableCellEditor".equals(e.getPropertyName()))
              if (table.isEditing())
                   processEditingStarted();
              else
                   processEditingStopped();
    }So when editing is started you need to determine the "adjacent" cell you want to repaint to the blue font is used. You would save the cell Rectangle so you can restore the font when editing is stopped.

  • How to select rows in the inner JTable rendered in an outer JTable cell

    I have wrriten the following code for creating cell specific renderer - JTable rendered in a cell of a JTable.
    table=new JTable(data,columnNames)
    public TableCellRenderer getCellRenderer(int row, int column)
    if ((row == 0) && (column == 0))
    return new ColorRenderer();
    else if((row == 1) && (column == 0))
    return new ColorRenderer1();
    else
    return super.getCellRenderer(row, column);
    ColorRenderer and ColorRenderer1 are two inner classes, which implement TableCellRenderer to draw inner JTable on the outer JTable cell, having 2 rows and 1 column each.
    Now what is happening the above code keeps executing continously, that is the classes are being initialised continously, inner JTables are rendered (drawn) continously, and this makes the application slow after some time. It throws java.lang.OutOfMemoryException.
    WHY IS IT SO??? I can't understand where's the bug..
    Any advice please???
    Moreover i want selections in inner tables and not on outer table, how can this be possible.
    I am working on this since a long time but have not yet found a way out...

    With your help i have overcome the problem of continous repeatition.
    The major problem which I am facing is, in selecting rows in the inner rendered JTables.
    I have added listener on outer JTable which select rows on the outer JTable, hence the complete inner JTable which being treated as a row, gets selected.
    The thing is i need to select the rows of inner rendered JTables,not the outer JTable.
    How to go about it??
    I have even added listener to inner rendered JTables, but only first row of every table gets selected.
    Please help....
    Thanks in advance.

  • How to automatically highlight / bold words in a JTable cell?

    how do i do it?
    i have an Object called Data (where toString() is the same as getDataName()).
    and i want the JTable to either highlight or bold specific words (using the bold HTML tags) that are present in a SortedSet.
    i do not want the dataName to be changed by directly manipulating the Object because the Data Objects were taken from the DB and i need the Objects and the records to be synchronised, and because the words in the SortedSet itself are subject to changes (add/edit/remove).
    thanks.

    Edit: removed
    db
    Cross posted
    http://www.java-forums.org/awt-swing/47138-how-automatically-highlight-bold-words-jtable-cell.html
    Edited by: Darryl Burke

  • JTable cell value doesn't change with user input

    I'm making a program that uses a custom table model (extends AbstractTableModel). The problem is when I type a value in one of the table cells, then press enter (or click outside the cell), the value goes back to what it was originally. So for example, a cell has "oldvalue", I type in "newvalue", press enter, and now the cell still reads "oldvalue". I figured the renderer would automatically update the cell by calling MyTableModel.setValueAt (...), but maybe I need a listener to do this? let me know. thanks

    alright, well basically I'm making a database manager
    and thought it would be easier to extend
    AbstractTableModel and then do all the queries inside
    the methods instead of listening for events. Second
    thing, I put a debug statement and setValueAt never
    gets called when you type in a new cell value. How
    does it update the cell then is my question?It's your TableModel bug but a much better advice would be that you should use
    DefaultTableModel instead of extending AbstractTableModel. The DefaultTableModel
    is usually more than enough for an ordinary JTable application.
    The simplest and standard way of handling DB data from JTable is updating
    vectors for DefaultTableModel data with your new DB data set. You don't need
    to worry about low-level event firing, cell editor control etc. if you use
    DefaultTableModel. See API documentation of DefaultTableModel closely.

Maybe you are looking for