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

Similar Messages

  • Jtable cell changed listen

    i build a table but i need a listener for any changed for my table, so i could validate at table
    Message was edited by:
    suryanto_so

    DefaultTableModel tablemodel = new DefaultTableModel(data,column);
    tablemodel.addTableModelListener(new InteractiveTableModelListener());
    public class InteractiveTableModelListener implements TableModelListener {
             public void tableChanged(TableModelEvent evt) {
                 if (evt.getType() == TableModelEvent.UPDATE) {
    }

  • JTable cell change

    Hi,
    How can I know when a cell in my JTable is modified ?
    Thanx,
    P

    I used this listener already but it was not notifed when there was a change in my model.
    Because it's a customized model I've added the fireTableCellUpdated()-method to the setValueAt() method of the model.
    Now it works fine and my listener is notified.
    Thanx,
    Piet

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

  • 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 Transfer On Table Changed Event

    Hi, sorry if this has been hashed out before but I have a JTable that when pressing the TAB key will transfer the focus from one column cell to the next column (same row). What I would like to do is that when a character is entered from the keyboard (a number in this case), the focus is automatically transferred to the next column. My JTable is configured as with custom layout and the DefaultTableCellRenderer. I'm assuming that I would have to have a key listener that acts on the numbers but from there, I'm not exactly sure what I need to do. I tried issuing transferFocus when the tableListener is fired on a cell change but it didn't do anything so I am a bit lost
    Any help here would be great!
    Thanks...
    Chris.

    Check out [Key Bindings|http://www.camick.com/java/blog.html?name=key-bindings]. It sounds like you want to "share an Action with a different KeyStroke".

  • Data changes in JTable cell.

    Hi all,
    On editing a cell in a Jtable ,necessary changes must get enforced in the corresponding cells of the same JTable.For example,I have fields called Quantity ,SalePrice and TotalAmount in a Jtable,where the Quantity field is editable.When i edit the Quantity value,a calculation (Changed Quantity *SalePrice)=TotalPrice must happen .Hence the Total Amount field must get Updated now.This must occur when I edit the Quantity and press Tab.No Button action is involved.Please tell me how to do this.the JTable does not use any TableModel.Thanks in advance.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    As I said in your other post, your table does have a model.
    What you seem to be saying is that your table has some calculated columns. If so then you should create an explicit table model so that when a cell is update the setValueAt() method performs any calculations based on this change and updates the rest of the model.
    Remember to fire the appropriate events after the change.

  • Jtable on cell changed event

    How can i treat an Jtable on cell changed event, not on value changed

    Do you mean cell selection changed? One way is to add a ListSelectionListener to both the table's and the table's ColumnModel's ListSelectionModels. Something likeListSelectionListener lsl = new ListSelectionListener() {
       public void valueChanged(ListSelectionEvent e) {
          System.out.println(e.getSource());
          ListSelectionModel lsm = (ListSelectionModel) e.getSource();
          if (!lsm.getValueIsAdjusting()) {
             System.out.println("Selection changed");
    table.getSelectionModel().addListSelectionListener(lsl);
    table.getColumnModel().getSelectionModel().addListSelectionListener(lsl);Note that simultaneous change of both row and column will generate two valueChanged events.
    If that's not what you wanted to know, ask a better question.
    [http://catb.org/~esr/faqs/smart-questions.html]
    db

  • Jtable cell listening to mouse event source

    Hi, I have a JTable with single cell selections enabled.
    I can also get the mouseClicked event working, but the cure is worse than the illness, because every cell I click on will cause a jframe to pop-up.
    Ideally only column 0 or 1 listens to the mouseClicked event.
    Can someone please tell mehow to work that into the JTable cell (sorry for the tediously long code, its only a small part)
    import javax.swing.JComponent;
    ...lots of import...
    public class CCYTable extends JPanel
      JTable newtable;
      JLabel tableHeader;
      public CCYFrame NewFrame;
      private boolean DEBUG = false;
      private int showInfoTimer = 10000; // info tip box will pop up for this period of time...
      // if both column and row selection are enabled, then individual cell selection
      // is also enabled.
      private boolean ALLOW_COLUMN_SELECTION = true;
      private boolean ALLOW_ROW_SELECTION = true;
      private boolean clickForDetail = true; // click on cell to launch frame with detail
      protected String[] colHeaderInfo =
        {"Name of Instrument, move mouse to instrument for general detail of service.",
          ...lots of text...
      // get values from database, use an "invisible column" for unique key
      // description, conditions etc from Oracle...
      String LoC = "Letter of Credit";
       ...more variable...
      public void init()
        //setSize(300,300);
        tableHeader = new JLabel("uy or Sell", JLabel.CENTER);
        setLayout(new BorderLayout());
        newtable = new JTable(new TableDefinition())
          //Put cell info here, from Oracle CellInfo varchar2
          public String getToolTipText (MouseEvent mevt)
            String info = null;
            java.awt.Point p = mevt.getPoint();
            int rowIndex = rowAtPoint(p);
            int colIndex = columnAtPoint(p);
            int realColIndex = convertColumnIndexToModel(colIndex);
            Object currentValue = getValueAt(rowIndex, colIndex);
            if (realColIndex == 0)
            { if (currentValue.equals(LoC))
              { info = "Click to read general description of our \"" + LoC + "\" service." ;
              ... ideally I would like to work the mouseClicked listener in here but... 
            return info;
          } // end of JComponent's method getToolTipText
          //Put table header info
          protected JTableHeader createDefaultTableHeader()
            return new JTableHeader(columnModel)
              public String getToolTipText(MouseEvent mevt)
                String tip = null;
                java.awt.Point p = mevt.getPoint();
                int index = columnModel.getColumnIndexAtX(p.x);
                int realIndex = columnModel.getColumn(index).getModelIndex();
                return colHeaderInfo[realIndex];
        if (clickForDetail)
          newtable.addMouseListener(new MouseAdapter()
            public void mouseClicked(MouseEvent mevt)
              { // ...but JTable wants it like this...
                // launch a new pop-up to replace the tool tip box
                NewFrame = new CCYFrame("blabla");
        ToolTipManager.sharedInstance().setDismissDelay(showInfoTimer);
        newtable.setPreferredScrollableViewportSize(new Dimension(770, 350));
        JScrollPane scrollpane = new JScrollPane(newtable);
        initColumnSizes(newtable);
        enableCellSelection(newtable);
        add("North", tableHeader);
        add("Center", scrollpane);
       * For sizing columns. If all column heads are wider than the column-cells'
       * contents, then just use column.sizeWidthToFit().
      private void initColumnSizes(JTable newtable)
        TableDefinition tblmodel = (TableDefinition)newtable.getModel();
        TableColumn column = null;
        Component comp = null;
        int headerWidth=0, cellWidth=0;
        Object[] longValues = tblmodel.longValues;
        TableCellRenderer headerRenderer = newtable.getTableHeader().getDefaultRenderer();
        TableCellRenderer rightRenderer = new RightRenderer();
        for (int i = 0; i < 7; i++)
          column = newtable.getColumnModel().getColumn(i);
          comp = headerRenderer.getTableCellRendererComponent(
                                 null, column.getHeaderValue(),
                                 false, false, 0, 0);
          headerWidth = comp.getPreferredSize().width;
          comp = newtable.getDefaultRenderer(tblmodel.getColumnClass(i)).
                          getTableCellRendererComponent(
                                 newtable, longValues,
    true, true, 0, i);
    cellWidth = comp.getPreferredSize().width;
    column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    TableColumn col2 = newtable.getColumnModel().getColumn(2);
    col2.setCellRenderer( rightRenderer );
    TableColumn col2Width = newtable.getColumnModel().getColumn(2);
    col2Width.setPreferredWidth(2);
    TableColumn col6 = newtable.getColumnModel().getColumn(6);
    col6.setCellRenderer( rightRenderer );
    TableColumn col6Width = newtable.getColumnModel().getColumn(6);
    col6Width.setPreferredWidth(2);
    }// end of method initColumnSizes
    private void enableCellSelection(JTable newtable)
    if (ALLOW_COLUMN_SELECTION)
    if (ALLOW_ROW_SELECTION) {newtable.setCellSelectionEnabled(true);}
    newtable.setColumnSelectionAllowed(true);
    ListSelectionModel colSM = newtable.getColumnModel().getSelectionModel();
    colSM.addListSelectionListener(new ListSelectionListener()
    public void valueChanged(ListSelectionEvent lsevt)
    if (lsevt.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)lsevt.getSource();
    if (lsm.isSelectionEmpty()) {}
    else
    //int selectedCol = lsm.getMinSelectionIndex();
    //NewFrame = new CCYFrame("more blabla!");
    }//end of method enableCellSelection
    ...a lot of code follows...
    TIA :-)

    Hi, thanks for the tip, but I get following compile-time error:
    <identifier> expected
    newtable.addMouseListener(new MouseAdapter()
    .............................................^
    package newtable does not exist
    newtable.addMouseListener(new MouseAdapter()
    ...............^
    2 errors
    And here is how I've modified the code :
    public class CCYTable extends JPanel
      JTable newtable;
      ...lots of variables...
      private boolean ALLOW_COLUMN_SELECTION = true;
      private boolean ALLOW_ROW_SELECTION = true;
      private boolean clickForDetail = true; // click on cell to launch frame with detail
      protected String[] colHeaderInfo =
        {"Name of Instrument, move mouse to instrument for general detail of service.",
          ...lots of text for tooltipbox...
      // get values from database, use an "invisible column" for unique key
      // description, conditions etc from Oracle...
       ...lots more String variables...
      public void init()
        //setSize(300,300);
        tableHeader = new JLabel("Bids and Offers", JLabel.CENTER);
        setLayout(new BorderLayout());
        newtable = new JTable(new TableDefinition())
          //Put cell info here, from Oracle CellInfo varchar2
          public String getToolTipText (MouseEvent mevt)
            String info = null;
            java.awt.Point p = mevt.getPoint();
            int rowIndex = rowAtPoint(p);
            int colIndex = columnAtPoint(p);
            int realColIndex = convertColumnIndexToModel(colIndex);
            Object currentValue = getValueAt(rowIndex, colIndex);
            if (realColIndex == 0)
            { if (currentValue.equals(LoC))
              { info = "Click to read general description of our \"" + LoC + "\" service." ;
            return info;
          } // end of JComponent's method getToolTipText
          newtable.addMouseListener(new MouseAdapter()  //  HELP: compiler throws error here !!!!!!!!
            public void mouseClicked(MouseEvent e)
              java.awt.Point p = mevt.getPoint();
              int rowIndex = rowAtPoint(p);
              int colIndex = columnAtPoint(p);
              int realColIndex = convertColumnIndexToModel(colIndex);
              Object currentValue = getValueAt(rowIndex, colIndex);
              if ((rowIndex == 0) and (colIndex == 0))
                // do stuff for this particular JTable cell ...
          //Put table header info
          protected JTableHeader createDefaultTableHeader()
            return new JTableHeader(columnModel)
              public String getToolTipText(MouseEvent mevt)
                String tip = null;
                java.awt.Point p = mevt.getPoint();
                int index = columnModel.getColumnIndexAtX(p.x);
                int realIndex = columnModel.getColumn(index).getModelIndex();
                return colHeaderInfo[realIndex];
        ToolTipManager.sharedInstance().setDismissDelay(showInfoTimer);
        newtable.setPreferredScrollableViewportSize(new Dimension(770, 350));
        JScrollPane scrollpane = new JScrollPane(newtable);
        initColumnSizes(newtable);
        enableCellSelection(newtable);
        add("North", tableHeader);
        add("Center", scrollpane);
      }On the other hand, this code works after a fashion but it is not what is needed because it listens to every JTable cell :
    public class CCYTable extends JPanel
      JTable newtable;
      ...unbelievably more variable definitions, etc...
      public void init()
        //setSize(300,300);
        tableHeader = new JLabel("Bids and Offers", JLabel.CENTER);
        setLayout(new BorderLayout());
        newtable = new JTable(new TableDefinition())
          //Put cell info here, from Oracle CellInfo varchar2
          public String getToolTipText (MouseEvent mevt)
            String info = null;
            java.awt.Point p = mevt.getPoint();
            int rowIndex = rowAtPoint(p);
            int colIndex = columnAtPoint(p);
            int realColIndex = convertColumnIndexToModel(colIndex);
            Object currentValue = getValueAt(rowIndex, colIndex);
            if (realColIndex == 0)
            { if (currentValue.equals(LoC))
              { info = "Click to read general description of our \"" + LoC + "\" service." ;
                if (rowIndex == 0)  // HELP:  compiles okay but won't specifically select rowIndex == 0 and colIndex == 0
                {this.addMouseListener(new clickListener(newtable, rowIndex, colIndex));
            return info;
          } // end of JComponent's method getToolTipText
         ... lots more code...
      // ==============================
      class clickListener extends MouseAdapter
        private JTable newtable;
        private int rowIndex;
        private int colIndex;
        public clickListener(JTable newtable, int rowIndex, int colIndex)
          this.newtable = newtable;
          this.rowIndex = rowIndex;
          this.colIndex = colIndex;
        public void mouseClicked(MouseEvent mevt)
          NewFrame = new CCYFrame("blablabla");
      }// end of method clickListenerIdeally I should be able to use a selection criteria like this :
    java.awt.Point p = mevt.getPoint();
    rowIndex = rowAtPoint(p);
    colIndex=colAtPoint(p);
    if ((rowIndex == 0) && (colIndex == 0)) {//do something}but this is going to be a bad Chrissy for me?

  • Code to change JTable cell color not working

    My code below is supposed to change the color
    of a single JTable cell however its not working.
    Could anyone please tell me why?
    Here's the code:
    import java.awt.*;
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class ColorTable extends JTable {
    public ColorTable() {
    AbstractTableModel tableModel = new AbstractTableModel() {
    public Class getColumnClass(int column) { return Integer.class; }
    public int getColumnCount() { return 6; }
    public int getRowCount() { return 10;}
    public Object getValueAt(int row,int col) { return new Integer(row * col); }
    setModel(tableModel);
    setDefaultRenderer(Integer.class,new ColorRenderer(Color.cyan));
    this.setRowSelectionAllowed(false);
    this.setCellSelectionEnabled(true);
    addMouseListener(new MouseAdapter() {
    private ColorRenderer renderer;
    private JColorChooser chooser = new JColorChooser();
    public void mousePressed(MouseEvent e) {
    if(e.getModifiers() == MouseEvent.BUTTON3_MASK) {
    System.out.print("rowAtPoint(e.getPoint())=" +rowAtPoint(e.getPoint()));
    System.out.print( "columnAtPoint(e.getPoint()))=" + columnAtPoint(e.getPoint()));
    renderer = (ColorRenderer)getCellRenderer(rowAtPoint(e.getPoint()), columnAtPoint(e.getPoint()));
    // chooser.setColor(renderer.getColor());
    renderer.setColor(chooser.showDialog((Component)e.getSource(),"Choose Cell Color",chooser.getColor()));
    class ColorRenderer extends DefaultTableCellRenderer {
    private Color cellColor;
    public ColorRenderer(Color color) { cellColor = color; }
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    System.out.print("row= " + row + "\n");
    System.out.print("column= " + column + "\n");
    System.out.print("OBJECT VALUE=" + value.toString());
    //Component comp = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    if (isSelected) {
    setOpaque(true);
    setBackground(cellColor);
    else {
    setBackground(Color.white);
    setForeground(Color.black);
    return this;
    public void setColor(Color color)
    cellColor = color;
    ColorTable.this.repaint();
    public Color getColor() { return cellColor; }
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    ColorTable table = new ColorTable();
    panel.add(table);
    frame.getContentPane().add(panel);
    frame.setSize(500,250);
    frame.setVisible(true);

    My code below is supposed to change the color
    of a single JTable cell however its not working.
    Could anyone please tell me why?
    Here's the code:
    import java.awt.*;
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class ColorTable extends JTable {
    public ColorTable() {
    AbstractTableModel tableModel = new AbstractTableModel() {
    public Class getColumnClass(int column) { return Integer.class; }
    public int getColumnCount() { return 6; }
    public int getRowCount() { return 10;}
    public Object getValueAt(int row,int col) { return new Integer(row * col); }
    setModel(tableModel);
    setDefaultRenderer(Integer.class,new ColorRenderer(Color.cyan));
    this.setRowSelectionAllowed(false);
    this.setCellSelectionEnabled(true);
    addMouseListener(new MouseAdapter() {
    private ColorRenderer renderer;
    private JColorChooser chooser = new JColorChooser();
    public void mousePressed(MouseEvent e) {
    if(e.getModifiers() == MouseEvent.BUTTON3_MASK) {
    System.out.print("rowAtPoint(e.getPoint())=" +rowAtPoint(e.getPoint()));
    System.out.print( "columnAtPoint(e.getPoint()))=" + columnAtPoint(e.getPoint()));
    renderer = (ColorRenderer)getCellRenderer(rowAtPoint(e.getPoint()), columnAtPoint(e.getPoint()));
    // chooser.setColor(renderer.getColor());
    renderer.setColor(chooser.showDialog((Component)e.getSource(),"Choose Cell Color",chooser.getColor()));
    class ColorRenderer extends DefaultTableCellRenderer {
    private Color cellColor;
    public ColorRenderer(Color color) { cellColor = color; }
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    System.out.print("row= " + row + "\n");
    System.out.print("column= " + column + "\n");
    System.out.print("OBJECT VALUE=" + value.toString());
    //Component comp = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    if (isSelected) {
    setOpaque(true);
    setBackground(cellColor);
    else {
    setBackground(Color.white);
    setForeground(Color.black);
    return this;
    public void setColor(Color color)
    cellColor = color;
    ColorTable.this.repaint();
    public Color getColor() { return cellColor; }
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    ColorTable table = new ColorTable();
    panel.add(table);
    frame.getContentPane().add(panel);
    frame.setSize(500,250);
    frame.setVisible(true);

  • Problem in event handling of combo box in JTable cell

    Hi,
    I have a combo box as an editor for a column cells in JTable. I have a event listener for this combo box. When ever I click on the JTable cell whose editor is combo box,
    I get the following exception,
    Exception occurred during event dispatching:
    java.lang.NullPointerException
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.setDispatchComponent(Unknown Source)
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.mousePressed(Unknown Source)
         at java.awt.AWTEventMulticaster.mousePressed(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Can any one tell me how to over come this problem.
    Thanks,
    Raghu

    Here's an example of the model I used in my JTable. I've placed 2 comboBoxes with no problems.
    Hope this helps.
    public class FileModel5 extends AbstractTableModel
    public boolean isEditable = false;
    protected static int NUM_COLUMNS = 3;
    // initialize number of rows to start out with ...
    protected static int START_NUM_ROWS = 0;
    protected int nextEmptyRow = 0;
    protected int numRows = 0;
    static final public String file = "File";
    static final public String mailName = "Mail Id";
    static final public String postName = "Post Office Id";
    static final public String columnNames[] = {"File", "Mail Id", "Post Office Id"};
    // List of data
    protected Vector data = null;
    public FileModel5()
    data = new Vector();
    public boolean isCellEditable(int rowIndex, int columnIndex)
    // The 2nd & 3rd column or Value field is editable
    if(isEditable)
    if(columnIndex > 0)
    return true;
    return false;
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c)
    return getValueAt(0, c).getClass();
    * Retrieves number of columns
    public synchronized int getColumnCount()
    return NUM_COLUMNS;
    * Get a column name
    public String getColumnName(int col)
    return columnNames[col];
    * Retrieves number of records
    public synchronized int getRowCount()
    if (numRows < START_NUM_ROWS)
    return START_NUM_ROWS;
    else
    return numRows;
    * Returns cell information of a record at location row,column
    public synchronized Object getValueAt(int row, int column)
    try
    FileRecord5 p = (FileRecord5)data.elementAt(row);
    switch (column)
    case 0:
    return (String)p.file;
    case 1:
    return (String)p.mailName;
    case 2:
    return (String)p.postName;
    catch (Exception e)
    return "";
    public void setValueAt(Object aValue, int row, int column)
    FileRecord5 arow = (FileRecord5)data.elementAt(row);
    arow.setElementAt((String)aValue, column);
    fireTableCellUpdated(row, column);
    * Returns information of an entire record at location row
    public synchronized FileRecord5 getRecordAt(int row) throws Exception
    try
    return (FileRecord5)data.elementAt(row);
    catch (Exception e)
    throw new Exception("Record not found");
    * Used to add or update a record
    * @param tableRecord
    public synchronized void updateRecord(FileRecord5 tableRecord)
    String file = tableRecord.file;
    FileRecord5 p = null;
    int index = -1;
    boolean found = false;
    boolean addedRow = false;
    int i = 0;
    while (!found && (i < nextEmptyRow))
    p = (FileRecord5)data.elementAt(i);
    if (p.file.equals(file))
    found = true;
    index = i;
    } else
    i++;
    if (found)
    { //update
    data.setElementAt(tableRecord, index);
    else
    if (numRows <= nextEmptyRow)
    //add a row
    numRows++;
    addedRow = true;
    index = nextEmptyRow;
    data.addElement(tableRecord);
    //Notify listeners that the data changed.
    if (addedRow)
    nextEmptyRow++;
    fireTableRowsInserted(index, index);
    else
    fireTableRowsUpdated(index, index);
    * Used to delete a record
    public synchronized void deleteRecord(String file)
    FileRecord5 p = null;
    int index = -1;
    boolean found = false;
    int i = 0;
    while (!found && (i < nextEmptyRow))
    p = (FileRecord5)data.elementAt(i);
    if (p.file.equals(file))
    found = true;
    index = i;
    } else
    i++;
    if (found)
    data.removeElementAt(i);
    nextEmptyRow--;
    numRows--;
    fireTableRowsDeleted(START_NUM_ROWS, numRows);
    * Clears all records
    public synchronized void clear()
    int oldNumRows = numRows;
    numRows = START_NUM_ROWS;
    data.removeAllElements();
    nextEmptyRow = 0;
    if (oldNumRows > START_NUM_ROWS)
    fireTableRowsDeleted(START_NUM_ROWS, oldNumRows - 1);
    fireTableRowsUpdated(0, START_NUM_ROWS - 1);
    * Loads the values into the combo box within the table for mail id
    public void setUpMailColumn(JTable mapTable, ArrayList mailList)
    TableColumn col = mapTable.getColumnModel().getColumn(1);
    javax.swing.JComboBox comboMail = new javax.swing.JComboBox();
    int s = mailList.size();
    for(int i=0; i<s; i++)
    comboMail.addItem(mailList.get(i));
    col.setCellEditor(new DefaultCellEditor(comboMail));
    //Set up tool tips.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for mail Id list");
    col.setCellRenderer(renderer);
    //Set up tool tip for the mailName column header.
    TableCellRenderer headerRenderer = col.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the Mail Id to see a list of choices");
    * Loads the values into the combo box within the table for post office id
    public void setUpPostColumn(JTable mapTable, ArrayList postList)
    TableColumn col = mapTable.getColumnModel().getColumn(2);
    javax.swing.JComboBox combo = new javax.swing.JComboBox();
    int s = postList.size();
    for(int i=0; i<s; i++)
    combo.addItem(postList.get(i));
    col.setCellEditor(new DefaultCellEditor(combo));
    //Set up tool tips.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for post office Id list");
    col.setCellRenderer(renderer);
    //Set up tool tip for the mailName column header.
    TableCellRenderer headerRenderer = col.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the Post Office Id to see a list of choices");
    }

  • JTable data changed

    Hello,
    I have a JTable, there i stored values form database.
    I also have a "Save" button in the form.
    When user opens o form he saw data form database in JTable. I need a listener is user has changed some value i a JTable. If yes i need to enable save button.
    Can somebody point me to some value change listener example o give some advice
    Thanks a lot

    You can provide your own text field component to the DefaultCellEditor. Then you can add a key listener to that text field:
        JTextField text = new JTextField();
        text.addKeyListener( new KeyAdapter() {
          public void keyTyped( KeyEvent e ) {
            // Enable your save button here.
            saveButton.setEnabled( true );
        DefaultCellEditor e = new DefaultCellEditor(  text );
        // Then set the cell editor into the JTable however you prefer.
        // I usually overwrite JTable's getCellEditor() and return the
        // custom cell editor to do this.-Mike

  • Different jpopup menus items depending on content in a Jtable cell

    Hi,
    Is it possible if a popup menu have different items in it, depending on the content of a jtable cell??
    I would be greatful if any one could point me in the right direction.
    Thanks
    Venus

    In the mouse listener where you are displaying the popup, change it as appropriate before displaying it.

  • Java3D in a JTable cell ?

    Hello,
    I would like to put a Canvas3D component in a JTable cell, is there a way to do that ?
    If not, I think it should be possible to only get a generated picture of the 3D scene with the off screen mode of the Canvas3D, and then put it as an ImageIcon of the JTable cell.
    I tried this, but I got this error message : "OpenGL 1.2 or better is required (GL_VERSION=1.1)" even though I have the 1.4 version...
    Anyway, I would prefer to find a way to put the Canvas3D component in the cell, in order to be able to use the mouse to change the 3D scene.
    Thank you

    Are you using an annonymous inner class for your mouse listener? I think this coudl cause some problems in your case.
    Try creating your own listener class e.g.
    class myListener extends MouseListener(){....}
    in this class, add a field such as 'name' - set with the constructor. So when you create your "outer table" write something like..
    outerTable.addMouseListener(new myListener("outer"));
    And when you create the inner table, write something like
    innerTable.addMouseListener(new myListener("inner"));
    Then when you capture Mouse click events, you can work out whether the click came from an outer table or inner table:
    public void mouseClicked(MouseEvent e){
    if(this.name.equals("inner")).....
    else.....
    In this way you should avoid the problem of knowing which table was clicked on...and still us the same mouse listener.
    I hope this is what you mean!
    Chris.

  • JButton "sticking" in a JTable Cell

    So I've modified the renderer and what not and slapped a button into a JTable Cell. The assignment requires it to turn red/green altrenativly when pressed. It works perfectly aside from the fact that the buttons appear to not "bounce back" when they switch colors. (i.e. They appear depressed when red and pressed when green). The code is below. any ideas?
    import java.awt.Color;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.JButton;
    public class ButtonTableModel extends AbstractTableModel {
         private static final long serialVersionUID = 1;
         private Object[][] rows = new Object[2][1];
         private String[] columns = new String[1];
         public ButtonTableModel() {
              for(int k = 0; k < rows.length; k++) {
                   JButton button3 = new JButton("222");
                   button3.setSize(200, 200);
                   button3.setBackground(Color.red);
                   button3.addMouseListener(new ColorChanger(button3));
                   rows[k][0] = button3;
              /*button = new JButton("Test Button");
              button.setBackground(Color.red);
              button.addMouseListener(new ColorChanger(button));
              button2 = new JButton("asdf");
              button2.setBackground(Color.red);
              button2.addMouseListener(new ColorChanger(button2));
              rows[0][0] = button;
              rows[1][0] = button2;*/
         private class ColorChanger implements MouseListener {
              private JButton callingButton; //Stores the button that added the Listener
              public ColorChanger(JButton pCallingButton) {  //Constructs a ColorChanger that stores a given JButton
                   callingButton = pCallingButton;
              public void mouseClicked(MouseEvent e) { //When callingButton is clicked, its color changes alternativly to green/red
                   if(isGreen(callingButton) == false)
                        callingButton.setBackground(Color.green);
                   else
                        callingButton.setBackground(Color.red);
              //The 4 methods below are unused leftovers specified by the MouseListener Interface
              public void mouseEntered(MouseEvent arg0) {
              public void mouseExited(MouseEvent arg0) {
              public void mousePressed(MouseEvent arg0) {
              public void mouseReleased(MouseEvent arg0) {
         private boolean isGreen(JButton pButton) { //Returns true if a button's background is green, false otherwise
              if(pButton.getBackground() == Color.green)
                   return true;
              return false;
         public int getColumnCount() { //Returns the number of Columns in a table
              return columns.length;
         public int getRowCount() { //Returns the number of rows in the table
              return rows.length;
         public String getColumnName(int pCollumnIndex) { //Returns the name of the collumn
              return columns[pCollumnIndex];
         public Object getValueAt(int pRow, int pColumn) { //Returns the value at given table coordinates
              return rows[pRow][pColumn];
         public boolean isCellEditable(int pRow, int pColumn) { //Returns true if a cell at given coordinates is editable, false otherwise
                  return false;
         public Class getColumnClass(int pColumnIndex) { //Retrieves the class of the objects in a column
              return getValueAt(0, pColumnIndex).getClass();
    import java.awt.Color;
    import java.awt.Point;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.JTable;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import javax.swing.table.TableCellRenderer;
    public class JButtonJTableTest extends JFrame {
         private static final long serialVersionUID = 1;
         private JTable table;
         private TableCellRenderer tableCellRenderer;
         private MouseEvent e2;
         private Class columnClass;
         private JButton button;
         private Point mousePos;
         private int mouseRow, mouseColumn;
         public JButtonJTableTest() {
              super("JButton Table Test");
              table = new JTable(); //Setup the table, assigning the new renderer and model
              tableCellRenderer = table.getDefaultRenderer(JButton.class);
              table.setDefaultRenderer(JButton.class, new JButtonRenderer(tableCellRenderer));
              table.setModel(new ButtonTableModel());
              table.setGridColor(Color.blue);
              table.addMouseListener(new MouseForwarder());
              table.setShowGrid(true);
              add(table); //Add the table to the content pane
         private class MouseForwarder implements MouseListener {
              public void mouseClicked(MouseEvent e) {
                   mousePos = new Point(e.getX(), e.getY()); //Assing mouse coordinates to a point data structure
                   mouseRow = table.rowAtPoint(mousePos);  //Ascertain the mouse's row & column
                   mouseColumn = table.columnAtPoint(mousePos);
                   if(mouseRow == -1 || mouseColumn == -1)  //Ensure that the column is within the table
                        return;
                   columnClass = table.getColumnClass(mouseColumn); //Ascertain the column's class
                   if(columnClass != JButton.class) //If the class is not JButton, exit MouseForwarder
                        return;
                   button = (JButton)table.getValueAt(mouseRow, mouseColumn); //Access the button where the mouse clicked
                   e2 = (MouseEvent)SwingUtilities.convertMouseEvent(table, e, button); //Forward click to button
                   button.dispatchEvent(e2); //Have button take action
                   table.repaint(); //Repaint the table to ensure proper button animation
              //The 4 methods below are unused methods from the MouseListener Interface
              public void mouseEntered(MouseEvent arg0) {
              public void mouseExited(MouseEvent arg0) {
              public void mousePressed(MouseEvent arg0) {
              public void mouseReleased(MouseEvent arg0) {
         public static void main(String[] args) { //Setup and run the window
              JButtonJTableTest test = new JButtonJTableTest();
              test.setSize(300, 300);
              test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              test.setVisible(true);
    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    public class JButtonRenderer implements TableCellRenderer {
         private TableCellRenderer defaultRenderer;
         private Component jTableButton;
         public JButtonRenderer(TableCellRenderer pRenderer) {
              defaultRenderer = pRenderer;
         public Component getTableCellRendererComponent(JTable pTable, Object pButton, boolean isSelected,
                                                                     boolean hasFocus, int pRow, int pCollumn) {
              try {
                   jTableButton = (Component)pButton;
                   return (Component)pButton;
              catch(ClassCastException exception) {
                   return defaultRenderer.getTableCellRendererComponent(pTable, pButton, isSelected,
                        hasFocus, pRow, pCollumn);
    }

    This question was crossposted into the Swing forum and should be answered there as that is the correct location for it http://forum.java.sun.com/thread.jspa?threadID=753812

Maybe you are looking for