JTable Cell Listener

Hello everybody,
i´ve got the following problem: My JTable consists out of 7 columns, column 1 and 2 are editable via Abstract Cell Editor. In column 1 the user can post for example 10:00, in column 2 12:00. In column 3 the difference should automatically be posted. You can call this column "duration". My code so far:
public class GenericCellEditor extends AbstractCellEditor implements TableCellEditor{
     private static final long serialVersionUID = 1L;
     private JTextField mField=new JTextField();
     public GenericCellEditor(final String pTable, String pFunction){
          mField.addFocusListener(new A4LGenericFocusListener(pFunction){
               @Override
               public void focusGained(FocusEvent arg0) {
               @Override
               public void focusLost(FocusEvent arg0) {
                    try {
                         super.getMMethod().invoke(null, new Object[] { pTable });
                    } catch (Exception e){
                         e.printStackTrace();
     @Override
     public Component getTableCellEditorComponent(JTable arg0, Object value,
               boolean arg2, int arg3, int arg4) {
          mField.setText((String) value);
        return mField;
     @Override
     public Object getCellEditorValue() {
          return ((JTextField) mField).getText();
}the method which is called in the focusLost Event:
static public void handleColumn1(String pSource) throws Exception  {
          int  lRow = Table.getTablesSelectedRow(pSource);
          int  lCol = Table.getTablesSelectedCol(pSource);
          A4LTable.setTableValueAt(pSource, lRow, lCol, "bla");
     }     and the function:
static public void addCellListener(String pTableHandle, int pColumn, String pFunction) throws Exception{
         if (!sContainer.getMMap().containsKey(pTableHandle)) {
            throw new Exception("Handler-Error: "  +pTableHandle+
" is refers not a Table");
        } else if (!(sContainer.getMMap().get(pTableHandle).getMObject() instanceof JTable)) {
            throw new Exception("Handler-Error: "  +pTableHandle+
" is refers not a Table");
        } else {
             JTable lTable=(JTable)sContainer.getMMap().get(pTableHandle).getMObject();
             lTable.getColumnModel().getColumn(pColumn).setCellEditor(new A4LGenericCellEditor(pTableHandle, pFunction));
    }As you can see, i´m adding a CellListener to the specified pColumn. This works fine so far. My problem begins now: the user edits the cell in column1 and row1. If he skips via tab to the next cell, the handleColumn1 function is called. But now Table.getTablesSelectedCol contains the wrong column, cause the user skipped to stop editing. How can I prevent this from happening? Table.getTablesSelectedCol needs to provide the cell of the focusEvent and not the cell which is selected via user tab. I hope i made my problem clear.
One more thing: Is there any chance realising my table without a AbstractTextEditor? Just adding a special CellListener to a specified column and cell of the table. If the user edits the specified cell, another cell will be edited automatically with a duration (in my case). Thank you for your help.
Best regards
StefanTmp

You could just add a TableModelListener and update the value in column 3 whenever column 1 or 2 is updated. It might be even easier with a custom (Default/Abstract)TableModel and override setValueAt() to update the value in column 3 when necessary.
@Override
public void setValueAt(int row, int column, Object value) {
  super.setValueA(row, column, value);
  if(column == 1 || column == 2) {
    super.setValueAt(row, 3, calculateDuration(
      getValueAt(row, 1), getValueAt(row, 2));
}

Similar Messages

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

  • JTable, cells lost focus

    How can I get or listen to event when my cell lost focus ??

    The correct answer is to... well, that should be saved for the Swing forum. or alternatively, its in the text for THE FIRST google result for "jtable cell listener".

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

  • 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

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

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

  • Implementing Copy and Paste on JTable cells.

    Hi to all,
    Can anybody suggest as how to impose copy and paste with Ctrl-C and Ctrl-V by using keys on JTable cells.
    Thanks in advance.
    khiz_eng

    First, add a key listener to the table itself (most likely in the constructor for your table), like so:
      addKeyListener(new KeyListener()
        public void keyTyped(KeyEvent e) {}
        public void keyReleased(KeyEvent e) {}
        public void keyPressed(KeyEvent e)
          tableKeyPressed(e);
      });Next, add the code for the "tableKeyPressed" method. Here's a skeleton you can use as a starting point (obviously, the exact code to copy and paste will depend on the nature of the data you are trying to transfer).
      protected void tableKeyPressed(KeyEvent e)
        // Get selected cols and rows:
        int[] selectedRows = getSelectedRows();
        int[] selectedCols = getSelectedColumns();
        // A "copy" is signified by either ctrl+c, meta+c, or the "copy" button on a Sun keyboard.
        // Unfortunately, Java does not abstract this for us, so we have to test each of these conditions:
        if ((e.getKeyCode() == KeyEvent.VK_COPY) ||
            ((e.getKeyCode() == KeyEvent.VK_C) && e.isControlDown()) ||
            ((e.getKeyCode() == KeyEvent.VK_C) && e.isMetaDown()))
          // Grab the cell(s) that are currently selected by using the selectedRows
          // and selectedCols arrays from above.  Then copy this data to the clipboard.
        // A "paste" is signified by either ctrl+v, meta+v, or the "paste" button on a Sun keyboard.
        // Again, Java does not abstract this for us, so each condition must be tested:
        else if ((e.getKeyCode() == KeyEvent.VK_PASTE) ||
             ((e.getKeyCode() == KeyEvent.VK_V) && e.isControlDown()) ||
             ((e.getKeyCode() == KeyEvent.VK_V) && e.isMetaDown()))
          // Make sure there is valid data in the clipboard.
          // If so, paste it into the selected cell(s).
      }(By the way, this code assumes that you are running on a Sun machine with a Sun keyboard. If you are only targeting windows boxes, then the only key press you really need to worry about is CTRL+C. There's no harm in leaving the other keys in, though.
    Hope that helps,
    Steve

  • 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

  • Can not show the JCheckBox in JTable cell

    I want to place a JCheckBox in one JTable cell, i do as below:
    i want the column "d" be a check box which indicates "true" or "false".
    String[] columnNames = {"a","b","c","d"};
    Object[][] rowData = {{"", "", "", Boolean.FALSE}};
    tableModel = new DefaultTableModel(rowData, columnNames);
    dataTable = new JTable(tableModel);
    dataTable.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(new JCheckBox()));
    But when i run it, the "d" column show the string "false" or "true", not the check box i wanted.
    I do not understand it, can you help me?
    Thank you very much!
    coral9527

    Do not use DefaultTableModel, create your own table model and you should implement the method
    getColumnClass to display the boolean as checkbox ...
    I hope the following colde snippet helps you :
    class MyModel extends AbstractTableModel {
              private String[] columnNames = {"c1",
    "c2"};
    public Object[][] data ={{Boolean.valueOf(true),"c1d1"}};
         public int getColumnCount() {
         //System.out.println("Calling getColumnCount");
         return columnNames.length;
    public int getRowCount() {
    //System.out.println("Calling row count");
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * 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();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    data[row][col] = value;
    fireTableCellUpdated(row, col);

  • Shading part of a JTable Cell dependent upon the value of the cell

    Hi
    Was hoping some one woudl be able to provide some help with this. I'm trying to create a renderer that will "shade" part of a JTable cell's background depending upon the value in the cell as a percentage (E.g. if the cell contains 0.25 then a quarter of the cell background will be shaded)
    What I've got so far is a renderer which will draw a rectangle whose width is the relevant percentage of the cell's width. (i.e. the width of the column) based on something similar I found in the forum but the part I'm struggling with is getting it to draw this rectangle in any cell other than the first cell. I've tried using .getCellRect(...) to get the x and y position of the cell to draw the rectangle but I still can't make it work.
    The code for my renderer as it stands is:
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    public class PercentageRepresentationRenderer extends JLabel implements TableCellRenderer{
         double percentageValue;
         double rectWidth;
         double rectHeight;
         JTable table;
         int row;
         int column;
         int x;
         int y;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              if (value instanceof Number)
                   this.table = table;
                   this.row = row;
                   this.column = column;
                   Number numValue = (Number)value;
                   percentageValue = numValue.doubleValue();
                   rectHeight = table.getRowHeight(row);
                   rectWidth = percentageValue * table.getColumnModel().getColumn(column).getWidth();
              return this;
         public void paintComponent(Graphics g) {
            x = table.getCellRect(row, column, false).x;
            y = table.getCellRect(row, column, false).y;
              setOpaque(false);
            Graphics2D g2d = (Graphics2D)g;
            g2d.fillRect(x,y, new Double(rectWidth).intValue(), new Double(rectHeight).intValue());
            super.paintComponent(g);
    }and the following code produces a runnable example:
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    public class PercentageTestTable extends JFrame {
         public PercentageTestTable()
              Object[] columnNames = new Object[]{"A","B"};
              Object[][] tableData = new Object[][]{{0.25,0.5},{0.75,1.0}};
              DefaultTableModel testModel = new DefaultTableModel(tableData,columnNames);
              JTable test = new JTable(testModel);
              test.setDefaultRenderer(Object.class, new PercentageRepresentationRenderer());
              JScrollPane scroll = new JScrollPane();
              scroll.getViewport().add(test);
              add(scroll);
         public static void main(String[] args)
              PercentageTestTable testTable = new PercentageTestTable();
              testTable.pack();
              testTable.setVisible(true);
              testTable.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }If anyone could help or point me in the right direction, I'd appreciate it.
    Ruanae

    This is an example I published some while ago -
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Fred120 extends JPanel
        static final Object[][] tableData =
            {1, new Double(10.0)},
            {2, new Double(20.0)},
            {3, new Double(50.0)},
            {4, new Double(10.0)},
            {5, new Double(95.0)},
            {6, new Double(60.0)},
        static final Object[] headers =
            "One",
            "Two",
        public Fred120() throws Exception
            super(new BorderLayout());
            final DefaultTableModel model = new DefaultTableModel(tableData, headers);
            final JTable table = new JTable(model);
            table.getColumnModel().getColumn(1).setCellRenderer( new LocalCellRenderer(120.0));
            add(table);
            add(table.getTableHeader(), BorderLayout.NORTH);
        public class LocalCellRenderer extends DefaultTableCellRenderer
            private double v = 0.0;
            private double maxV;
            private final JPanel renderer = new JPanel(new GridLayout(1,0))
                public void paintComponent(Graphics g)
                    super.paintComponent(g);
                    g.setColor(Color.CYAN);
                    int w = (int)(getWidth() * v / maxV + 0.5);
                    int h = getHeight();
                    g.fillRect(0, 0, w, h);
                    g.drawRect(0, 0, w, h);
            private LocalCellRenderer(double maxV)
                this.maxV = maxV;
                renderer.add(this);
                renderer.setOpaque(true);
                renderer.setBackground(Color.YELLOW);
                renderer.setBorder(null);
                setOpaque(false);
                setHorizontalAlignment(JLabel.CENTER);
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)
                final JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
                if (value instanceof Double)
                    v = ((Double)value).doubleValue();
                return renderer;
        public static void main(String[] args) throws Exception
            final JFrame frame = new JFrame("Fred120");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(new Fred120());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.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

Maybe you are looking for