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?

Similar Messages

  • Multiple Buttons in JTable Headers:  Listening for Mouse Clicks

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

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

  • JTable Cell Listener

    Hello everybody,
    i&acute;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&acute;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));
    }

  • How to make the row header of the JTable respond to mouse events?

    Is there an easy way to enable the row header of a JTable so it listens to mouse events? I have put a button in the first cell of the row header but I can't click in it.
    I'm asking for an easy way because I've seen some fairly complicated examples on the web that seem close to what I want but I was hoping something simple like getRowHeader().setEnabled(true) would do the trick for my case...

    What's your row header, another JTable or something else? Check out camickr's [url http://tips4java.wordpress.com/2009/07/12/table-button-column/]Table Button Column.
    db
    edit Or to get better help sooner, post a [url http://mindprod.com/jgloss/sscce.html]SSCCE (Short, Self Contained, Compilable and Executable) example that demonstrates the problem.
    Edited by: Darryl Burke

  • Mouse events listener

    I'm having trouble listening for mouse events in Bridge CS6.
    This example script works well in Photoshop and Toolkit, but not in Bridge:
    var w =new Window ("dialog");
    var b = w.add ("button", undefined, "Qwerty");
    b.addEventListener("click", function (k){whatsup (k)});
    function whatsup (p)
      if(p.button == 2){ $.writeln ("Right-button clicked.") }
      if(p.shiftKey){ $.writeln ("Shift key pressed.") }
      $.writeln ("X: "+ p.clientX);
      $.writeln ("Y: "+ p.clientY);
    w.show ();
    Other event types like resize or focus work well.
    The event types that seem to be broken are: mousedown, mouseup, mouseover, mouseout, click
    Is there a work-around to this problem?

    Only the video edition team is using CC.
    We tried 2 times, on May and July to install 1 PC with CC and the apps (Photoshop and Bridge included) crashed several times.
    CS6 still is more stable.
    For my surprise, 90% of the code we have developed still works on photoshop/Bridge and now we are installing our 'private' company cloud network so my team will be editing also the photos from US on real time.
    Recently I have had success in discovering simple tricks regarding Bridge that anyone needs or uses, but crucial to hard workflows like the one we have.
    In that sense, may be next season we will be able to upgrade to cloud CC
    We'll see…

  • 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 catch the mouse event from the JTable cell of  the DefaultCellEditor

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

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

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

  • Mouse event not working on JTable in JAVA 1.4.2

    mouse event is not recognised on empty table when using with java 1.4.2. Please specify if there is any chnge done for mouse event capture for table from java 1.3.1 to java 1.4.2.
    since mouse events are working fine for JTableHeader.
    if anybody have an idea please let me know.

    Hi
    JTable is there on JPanel . same code is working in JAVA 1.3.1
    actually its a bug in java 1.4.2 ( ref. bug_id=4940522 )
    here is the code reference..
    public class TableEditor extends JPanel
    �implements ListSelectionListener, Selector, Editor
    private JTable�myTable;
    private JPopupMenu myPopup;
    private Vector�myActions;
    private Vector�myListeners;

    public TableEditor(String anAssociation, Editor anEditor, int type)
    super(new GridLayout(1,1));

    myListeners = new Vector();
    myActions�= new Vector();
    myPopup�= new JPopupMenu();
    myTable�= new JTable();
    ��
    myTable.getSelectionModel().addListSelectionListener(this);
    myTable.addMouseListener(new MouseAdapter() {
    �public void mouseClicked(MouseEvent me)
    �{
    � if ((me.getModifiers() & MouseEvent.BUTTON3_MASK) != 0)
    � {
    ��// Update actions in case ListSelectionModel are out of sync.
    ��for (int i = 0; i < myActions.size(); i++)
    ��{
    Object o = myActions.elementAt(i);
    if (o instanceof SelectorAction)
    ((SelectorAction)o).check();
    ���}
    myPopup.show(myTable, me.getX(), me.getY());
    �}
    // Added mouse listener to JTableHeader
    // This is a temporary solution to open popup menu on blank table,
    // as in Java 1.4.2 no mouse event captured on blank table.
    // So for now we will capture the event from the table header.
    JTableHeader myTableHeader = myTable.getTableHeader();
    myTableHeader.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent me)
    �{
    if ((me.getModifiers() & MouseEvent.BUTTON3_MASK) != 0)
    // Update actions in case ListSelectionModel are out of sync.
    for (int i = 0; i < myActions.size(); i++)
    ��{
    Object o = myActions.elementAt(i);
    if (o instanceof SelectorAction)
    ((SelectorAction)o).check();
    ���}
    myPopup.show(me.getComponent(), me.getX(), me.getY());
    � }
    �});
    The solution given is temporary ( adding JTableHeader component)..
    we want to retain the same functionality .. mouse event should get captured on empty table only..

  • JTable cell under Mouse positin?

    I have a need to update a control with information about a JTable cell that is currently under the Mouse pointer.
    No clicking, just moving the mouse around updates the other control with information depending on which cell is currently under the Mouse pointer.
    How Can I translate a mouse position into a row,col for the cell?

    Generally I assume these kinds of problems are either obvious problems in my code (at least, obvious to other people) or obscure interactions that are are royal PITA to track down.
    Apparently not in this case.
    * TestJTable.java
    * Created on Sep 14, 2010, 9:41:09 PM
    package testthing;
    import java.awt.Point;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.GroupLayout;
    import javax.swing.GroupLayout.Alignment;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.LayoutStyle.ComponentPlacement;
    import javax.swing.WindowConstants;
    import javax.swing.table.DefaultTableModel;
    * @author jlussmyer
    public class TestJTable extends javax.swing.JFrame {
        /** Creates new form TestJTable */
        public TestJTable() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            jScrollPane1 = new JScrollPane();
            tblTest = new JTable();
            lblInfo = new JLabel();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            tblTest.setModel(new DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            tblTest.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent evt) {
                    tblTestMouseClicked(evt);
            jScrollPane1.setViewportView(tblTest);
            lblInfo.setText("jLabel1");
            GroupLayout layout = new GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(Alignment.LEADING)
                .addComponent(lblInfo, GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
                .addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            layout.setVerticalGroup(
                layout.createParallelGroup(Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 275, GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addComponent(lblInfo)
                    .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            pack();
        }// </editor-fold>                       
        private void tblTestMouseClicked(MouseEvent evt) {                                    
            String txt = evt.getPoint().x + "," + evt.getPoint().y;
            int row = tblTest.rowAtPoint(evt.getPoint());
            Point pt = new Point(evt.getPoint());
            do {
                pt.y--;
            } while (tblTest.rowAtPoint(pt) == row);
            lblInfo.setText(txt + " row=" + row + ", pt.y=" + pt.y + ", " + tblTest.rowAtPoint(pt));
            return;
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TestJTable().setVisible(true);
        // Variables declaration - do not modify                    
        private JScrollPane jScrollPane1;
        private JLabel lblInfo;
        private JTable tblTest;
        // End of variables declaration                  
    }

  • Capturing events from a JCheckBox in a JTable cell

    I am trying to capture item state changed event from a JCheckbox in a JTable. When user selects checkbox I do insert in database and on deselect I do delete from database. The item state changed event is not firing correctly...can you please tell me what I am doing wrong. My JTable uses CustomModel which is used by many other apps. So I can not really modify CustomModel only to work with my JTable. Here is my code.
    public class MyClass extends JPanel
    .....some code to add panel, jscorollpane, etc.
    ResultSet res;
    GUI gui; //Custom Class to deal with different GUI layouts
    JTable myJTable = new JTable();
    GUI.CustomModel custModel;
    public void init()
         displayJTable();
    attachCheckBoxListeners();
    private void displayForms()
         res = //resultset from DB
    Vector cols = new Vector(10);
    cols.addElement(new Integer(1);
    gui.DisplayResultSetinTabel(res, myJtable, cols, null);
    custModel= (GUI.CustomModel) ((TableSorter) myJTable.getModel()).getModel();
    custModel.setEditableColumn(0, true);
    //Attach CheckBox Listener to all the checkbox in JTable
    private void attachCheckBoxListeners()
    for(int row = 0; row< myJTable.getRowCount(); row++)
    Object val = cm.getValueAt(row, 0);
    final JCheckBox jcb = (JCheckBox) gridForms.getCellEditor(row, 0).getTableCellEditorComponent(gridForms, val, true, row, 0);
    jcb.addItemListener( new java.awt.event.ItemListener() // Add Item Listener to trap events
    public void itemStateChanged(java.awt.event.ItemEvent event)
                   if(myJtable.getSelectedRow() == -1) // if no row is selected in table return
                        return;
                   try               
                   if (res.absolute(myJtable.getSelectedRow())+1))
         if(jcb.isSelected())
    saveData();();      
         else
    deleteData();
         catch(Exception e)
    System.out.println("ERROR ");
    } //end of AttachCheckBoxListeners ()
    private void SaveData() {}
    private void DeleteData() {}
    Okay....the problem is when JCheckBox state is changed (by user) from Selected to Deselected itemStateChanged() is fired and it does delete from database. then again itemStateChanged() called it detects Jcheckbox as selected and does inseret in database. On Jtable gui...that checkbox is still shown as desected.
    Please tell me what is going on here.....
    Thank you.

    In short - never listen to low-level events from editorComponents (low-level meaning everything below - and most of the time including - a editingStopped/editingCancelled of the cellEditor). Your problem belongs to the model realm - save if a cell value is changed - so solve it in the model realm by listening to event from the tableModel and trigger your business logic when you detect a change in that particular cell value.
    Greetings
    Jeanette

  • JTable Cell Change Listener

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

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

  • How to distinguish is cell get key event or mouse event in table?

    Hi!
    I have a JTable.
    1.Select cell and double click. As result caret is show
    2.Select cell and start type. As result caret is show
    How distinguish is caret is show, because cell get mouse event or key event?
    Thank you.

    Hm ...
    the problem with the key events is, that they are partically taking place in an editor component - but the double click of the mouse clicked on a cell, which is not currently edited, can be get by a MouseListener added to the JTable.
    My idea to that is as follows - hold the double_clicked state in a boolean variable hold by your JTable subclass - it is set by a MouseListener added to the JTable - and reset by the overwritten prepareEditor(...) method. This method should do the following:
    // say, double_clicked is a boolean field in your JTable subclass
    public Component prepareEditor(TableCellEditor editor,int row,int column) {
    Component c = super.prepareEditor(editor,row,column);
    if ((!double_clicked)&&(c instanceof JTextField)) { ((JTextField) c).setText(""); }
    double_clicked = false;
    return c;
    }now you have only to implement an add a MouseListener to your JTable subclass which detects this double click and sets the double_clicked field accordingly.
    This is an idea on the fly - hope it is helpful for you.
    greetings Marsian

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

  • Multiple JButtons inside JTable cell - Dispatch mouse clicks

    Hi.
    I know this subject has already some discussions on the forum, but I can't seem to find anything that solves my problem.
    In my application, every JTable cell is a JPanel, that using a GridLayout, places vertically several JPanel's witch using an Overlay layout contains a JLabel and a JButton.
    As you can see, its a fairly complex cell...
    Unfortunately, because I use several JButtons in several locations inside a JTable cell, sometimes I can't get the mouse clicks to make through.
    This is my Table custom renderer:
    public class TimeTableRenderer implements TableCellRenderer {
         Border unselectedBorder = null;
         Border selectedBorder = null;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                   boolean hasFocus, int row, int column) {
              if (value instanceof BlocoGrid) {
                   if (isSelected) {
                        if (selectedBorder == null)
                             selectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getSelectionBackground());
                        ((BlocoGrid) value).setBorder(selectedBorder);
                   } else {
                        if (unselectedBorder == null)
                             unselectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getBackground());
                        ((BlocoGrid) value).setBorder(unselectedBorder);
              return (Component) value;
    }and this is my custom editor (so clicks can get passed on):
    public class TimeTableEditor extends AbstractCellEditor implements TableCellEditor {
         private TimeTableRenderer render = null;
         public TimeTableEditor() {
              render = new TimeTableRenderer();
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int column) {
             if (value instanceof BlocoGrid) {
                  if (((BlocoGrid) value).barras.size() > 0) {
                       return render.getTableCellRendererComponent(table, value, isSelected, true, row, column);
             return null;
        public Object getCellEditorValue() {
            return null;
    }As you can see, both the renderer and editor return the same component that cames from the JTable model (all table values (components) only get instantiated once, so the same component is passed on to the renderer and editor).
    Is this the most correct way to get clicks to the cell component?
    Please check the screenshot below to see how the JButtons get placed inside the cell:
    http://img141.imageshack.us/my.php?image=calendarxo9.jpg
    If you need more info, please say so.
    Thanks.

    My mistake... It worked fine. The cell span code was malfunctioning. Thanks anyway.

Maybe you are looking for

  • How to create a single login for multiple apps on tomcat server?

    Hello, I am running the most recent versions of apache and tomcat on several dells with XP pro. When I login to an app I have created, a session variable is set, but when I browse to one of the other apps on the same computer, it does not recognize t

  • Post customer invoice without line items.

    Ppl, I am extracting customer invoice data from an external sytem and data consists of invoice header with the invoice total but no line items.How can i post this invoice in FI. what is the meaning of posting in FI if i am not posting to GL or AR? Wh

  • Spell checker in Pages 08

    Hi, I am trying out iwork 08 as a possible replacement for Office 04. Lately I have been getting a Cannot load spellchecker error popup whenever I try to start Pages. How do I fix this annoyance? Thanks, Steve

  • Topics won't open in RH

    I have a sick feeling that this may not be a RH issue - Running RH 6, over the past few days, it's been getting crankier - projects take > 1minute to open, randomly shuts itself down, but I was still able to edit and compile. Then, the last time I op

  • How to change to ssd on macbook

    hi im very new to changing parts on my mac and wanted to know how i change my hhd to a ssd and what to do after i turn it on ,iv looked on the net but cant find any clear help ,many thanks marcus