Problem w/ MouseMotionListener on JTable cell

Hey everyone,
I am using a MouseMotionListener on a JTable, and in most cases it works fine. The case where it does NOT work as I would expect is when you are editing a cell. In that case, events do not register when the mouse is moving over the cell being edited. I'm assuming that for some reason the cell editor maybe is receiving the events... but I'm not sure that is the case, and if it is, not sure how to deal with it. Here's a very basic example:
***************** begin code example ************************************
public class Main extends JFrame {
/** Creates a new instance of Main */
public Main() {
this.setLayout(new BorderLayout());
JPanel panel = new JPanel();
JTable theTable = new JTable(1,1);
theTable.addMouseMotionListener(new MouseMotionListener() {
               public void mouseDragged(MouseEvent e) {
                    // TODO Auto-generated method stub
               public void mouseMoved(MouseEvent e) {
                    System.out.println("Mouse Moved");
panel.add(theTable);
this.add(panel,BorderLayout.NORTH);
this.setSize(100,100);
setVisible(true);
* @param args the command line arguments
public static void main(String[] args) {
Main main = new Main();
***************** end code example **************************************
Now, what I want to do is be able to have a listener not only on the table, but also on the cells (even when they are being edited). It is worth noting that the listener still functions around the borders of the cell... just not when mousing over the cell itself. What is going on with this? What is the best way for me to achieve my desired results?
Thanks in advance,
Jared

Thanks for the tip on code formatting tags camickr. I'm (obviously) new to the forums.
I am using "balloon tool tips" (can be seen here: https://balloontip.dev.java.net) to display information about the columns. The way I am currently doing it is that I have a MouseMotionListener on the entire JTable, and I attach the balloon tool tip to the header directly above the center of the column that the mouse is over. The way I am able to always know where to attach the balloon tool tip at the top is by using the events from the MouseMotionListener, as well as the X coordinate provided by the event. It works wonderfully... until one of the cells is being edited. At that point it works wonderfully on every part of the JTable except that one cell.
Does that answer your question?
Thanks again,
Jared

Similar Messages

  • Problem in jtable cell

    Hi
    I am facing one problem. there is some data should be displayed in Jtable cell.
    The thing is that the whole data shall be visible in the cell.. for this I am writing one renderer.. but I could not find the desire solution.. please check it out
    class Item_Details extends JFrame {
        ApsJTable itemTable = null;
         ApsJTable imageTable = null;     
         ArrayList data = new ArrayList();
         String[] columns = new String[2];
         ArrayList data1 = new ArrayList();
         String[] columns1 = new String[2];
         ItemTableModel itemTableModel = null;
         ItemTableModel itemTableModel1 = null;
         public Item_Details()
              super("Item Details");          
             this.setSize(600,100);
              this.setVisible(true);
             init();          
         private void init(){
              ////////////// Get data for first Table Model  ////////////////////////////
              data = getRowData();
              columns = getColData();
              System.out.println(columns[0]);
             itemTableModel = new ItemTableModel(data,columns);
             /////////////Get Data for Second Table Model //////////////////////////////
              try{
                        data1 = getRowData1();
                 }catch(Exception e){}
              columns1 = getColumns1();
             itemTableModel1 = new ItemTableModel(data1,columns1);
             ///////////// Set Data In Both Table Model //////////////////////////////////
              itemTable = new ApsJTable(itemTableModel);
              imageTable = new ApsJTable(itemTableModel1);
              this.itemTable.setShowGrid(false);
              this.imageTable.setShowGrid(false);
              this.itemTable.setColumnSelectionAllowed(false);
              this.imageTable.setColumnSelectionAllowed(false);
              System.out.println(itemTable.getColumnCount());
              this.imageTable.setRowHeight(getImageHeight()+3);
              JScrollPane tableScrollPane = new JScrollPane(this.imageTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              tableScrollPane.setRowHeaderView(this.itemTable);
              tableScrollPane.getRowHeader().setPreferredSize(new Dimension(800, 0));
              itemTable.getTableHeader().setReorderingAllowed(false);
              itemTable.setColumnSelectionAllowed(false);
              //itemTable.setRowHeight(25);
              itemTable.setCellSelectionEnabled(false);
              itemTable.setFocusable(false);
              imageTable.getTableHeader().setReorderingAllowed(false);
              imageTable.setFocusable(false);
              imageTable.setCellSelectionEnabled(false);
              //tableScrollPane.setOpaque(false);
              itemTable.setAutoCreateColumnsFromModel(false);
              int columnCount = itemTable.getColumnCount();
              for(int k=0;k<columnCount;k++)
              /*     TableCellRenderer renderer = null;
                   TableCellEditor editor = null;
                   renderer = new TextAreaCellRenderer();     // NEW
                   editor = new TextAreaCellEditor();     
                   TableColumn column = new TableColumn(k,itemTable.getColumnModel().getColumn(k).getWidth(),renderer, editor);
                        itemTable.addColumn(column);*/
                   itemTable.getColumnModel().getColumn(k).setCellRenderer(new MultiLineCellRenderer());
                   //itemTable.getColumnModel().getColumn(k).setCellEditor(new TextAreaCellEditor());
    ////////////---------------------- Here background color is being set--------------//////////////////
              this.imageTable.getParent().setBackground(Color.WHITE);
              this.itemTable.getParent().setBackground(Color.WHITE);
              tableScrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER,this.itemTable.getTableHeader());
              getContentPane().add(tableScrollPane,BorderLayout.CENTER);
              getContentPane().setVisible(true);
         public static void main(String[] str){
              com.incors.plaf.alloy.AlloyLookAndFeel.setProperty("alloy.licenseCode", "2005/05/28#[email protected]#1v2pej6#1986ew");
              try {
                javax.swing.LookAndFeel alloyLnF = new com.incors.plaf.alloy.AlloyLookAndFeel();
                javax.swing.UIManager.setLookAndFeel(alloyLnF);
              } catch (javax.swing.UnsupportedLookAndFeelException ex) {
              ex.printStackTrace();
              Item_Details ID = new Item_Details();
              ID.setVisible(true);
    public ArrayList getRowData()
         ArrayList rowData=new ArrayList();
         Hashtable item = new Hashtable();
         item.put(new Long(0),new String("Item No:"));
         item.put(new Long(1),new String("RED-1050"));
         rowData.add(0,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Description:"));
         item.put(new Long(1),new String("SYSTEM 18 mbh COOLING 13 mbh HEATING 230/208 v POWER AIRE "));
         rowData.add(1,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Stage:"));
         item.put(new Long(1),new String("Draft"));
         rowData.add(2,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Price: "));
         item.put(new Long(1),new String(" 999.00"));
         rowData.add(3,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(4,item);
         /*item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(5,item);
         item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(6,item);
         item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(7,item);
         return rowData;
    public String[] getColData()
         String[] colData = new String[]{"Attribute","Value"};
         return colData;
    public ArrayList getRowData1()throws MalformedURLException{
         ArrayList rowData = new ArrayList();
         Hashtable item = new Hashtable();
         String str = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
         URL url = new URL(str);
         ImageIcon ic = new ImageIcon(url);
         ImageIcon scaledImage = new ImageIcon(ic.getImage().getScaledInstance(getImageHeight(), -1,Image.SCALE_SMOOTH));
         item.put(new Long(0), scaledImage);
         rowData.add(0,item);
         String str1 = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
         URL url1 = new URL(str1);
         ImageIcon ic1 = new ImageIcon(url1);
         ImageIcon scaledImage1 = new ImageIcon(ic1.getImage().getScaledInstance(120, -1,Image.SCALE_DEFAULT));
         item.put(new Long(0),scaledImage1);
         rowData.add(1,item);
         return rowData;
    public String[] getColumns1(){
         String[] colData = new String[]{"Image"}; 
         return colData;
    public int getImageHeight(){
         ImageIcon ic = new ImageIcon("c:\\image\\ImageNotFound.gif");
         return ic.getIconHeight();
    class MultiLineCellRenderer extends JTextArea implements TableCellRenderer {
           public MultiLineCellRenderer() {
                setLineWrap(true);
                setWrapStyleWord(true);
             JScrollPane m_scroll = new JScrollPane(this,
                       JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                       JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
             setOpaque(true);
           public Component getTableCellRendererComponent(JTable table, Object value,
                        boolean isSelected, boolean hasFocus, int row, int column) {
                /*if (isSelected) {
               setForeground(table.getSelectionForeground());
               setBackground(table.getSelectionBackground());
             } else {
               setForeground(table.getForeground());
               setBackground(table.getBackground());
            // setFont(table.getFont());
            /* if (hasFocus) {
               setBorder( UIManager.getBorder("Table.focusCellHighlightBorder") );
               if (table.isCellEditable(row, column)) {
                 setForeground( UIManager.getColor("Table.focusCellForeground") );
                 setBackground( UIManager.getColor("Table.focusCellBackground") );
             } else {
               setBorder(new EmptyBorder(1, 2, 1, 2));
             int width = table.getColumnModel().getColumn(column).getWidth();
              //setSize(width, 1000);
              int rowHeight = getPreferredSize().height;
              if (table.getRowHeight(row) != rowHeight)
                   table.setRowHeight(row, rowHeight);
             setText((value == null) ? "" : value.toString());
             return this;
         }what wrong with this code..
    Thanks

    In summary, you have one or more columns for which the data must be wholly visible - correct? If you need all the columns to show the whole of their data, you are goinf to have to expand the table, otherwise you can expand a column with something like
    myTable.getColumnModel().getColumn(whichever).setPreferredWidth(whatever);

  • Problem in JTable cell renderer

    Hi
    One problem in JTable cell. Actually I am using two tables while I am writing renderer for word raping in first table .. but it is affected in last column only remain is not being effected�. Please chaek it out what is exact I am missing�
    Thanks
    package com.apsiva.tryrowmerge;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.EventObject;
    import java.util.Hashtable;
    import java.net.*;
    import javax.swing.*;
    import javax.swing.border.Border;
    import javax.swing.border.EmptyBorder;
    import javax.swing.event.*;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    class Item_Details extends JFrame {
        ApsJTable itemTable = null;
         ApsJTable imageTable = null;     
         ArrayList data = new ArrayList();
         String[] columns = new String[2];
         ArrayList data1 = new ArrayList();
         String[] columns1 = new String[2];
         ItemTableModel itemTableModel = null;
         ItemTableModel itemTableModel1 = null;
         public Item_Details()
              super("Item Details");          
             this.setSize(600,100);
             this.setBackground(Color.WHITE);
              this.setVisible(true);
             init();          
         private void init(){
              ////////////// Get data for first Table Model  ////////////////////////////
              data = getRowData();
              columns = getColData();
              System.out.println(columns[0]);
             itemTableModel = new ItemTableModel(data,columns);
             /////////////Get Data for Second Table Model //////////////////////////////
              try{
                        data1 = getRowData1();
                 }catch(Exception e){}
              columns1 = getColumns1();
             itemTableModel1 = new ItemTableModel(data1,columns1);
             ///////////// Set Data In Both Table Model //////////////////////////////////
              itemTable = new ApsJTable(itemTableModel);
              imageTable = new ApsJTable(itemTableModel1);
              this.itemTable.setShowGrid(false);
              this.imageTable.setShowGrid(false);
              this.itemTable.setColumnSelectionAllowed(false);
              this.imageTable.setColumnSelectionAllowed(false);
              System.out.println(itemTable.getColumnCount());
              this.imageTable.setRowHeight(getImageHeight()+3);
              JScrollPane tableScrollPane = new JScrollPane(this.imageTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              tableScrollPane.setRowHeaderView(this.itemTable);
              //itemTable.getColumnModel().getColumn(0).setMaxWidth(200);
              itemTable.getColumnModel().getColumn(0).setPreferredWidth(200);
              itemTable.getColumnModel().getColumn(1).setPreferredWidth(600);
              tableScrollPane.getRowHeader().setPreferredSize(new Dimension(800, 0));
              itemTable.getTableHeader().setResizingAllowed(false);
              itemTable.getTableHeader().setReorderingAllowed(false);
              itemTable.setColumnSelectionAllowed(false);
              //itemTable.setRowHeight(25);
              itemTable.setCellSelectionEnabled(false);
              itemTable.setFocusable(false);
              imageTable.getTableHeader().setReorderingAllowed(false);
              imageTable.setFocusable(false);
              imageTable.setCellSelectionEnabled(false);
              //tableScrollPane.setOpaque(false);
              itemTable.setAutoCreateColumnsFromModel(false);
              int columnCount = itemTable.getColumnCount();
              for(int k=0;k<columnCount;k++)
                   TableCellRenderer renderer = null;
                   TableCellEditor editor = null;
                   renderer = new TextAreaCellRenderer();     // NEW
              //     editor = new TextAreaCellEditor();     
              //     TableColumn column = new TableColumn(k,itemTable.getColumnModel().getColumn(k).getWidth(),renderer, editor);
                   System.out.println(k);
                   itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);          
                   //itemTable.getColumnModel().getColumn(k).setCellEditor(editor);
                   /*itemTable.getColumnModel().getColumn(1).setCellRenderer(new TextAreaCellRenderer());
                   itemTable.getColumnModel().getColumn(1).setCellEditor(new TextAreaCellEditor());*/
    //               itemTable.setShowGrid(false);
                   //itemTable.addColumn(column);
                   //itemTable.getColumnModel().getColumn(k).setCellRenderer(new MultiLineCellRenderer());
                   //itemTable.getColumnModel().getColumn(k).setCellEditor(new TextAreaCellEditor());
    ////////////---------------------- Here background color is being set--------------//////////////////
              this.imageTable.getParent().setBackground(Color.WHITE);
              this.itemTable.getParent().setBackground(Color.WHITE);
              tableScrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER,this.itemTable.getTableHeader());
              getContentPane().add(tableScrollPane,BorderLayout.CENTER);
              getContentPane().setVisible(true);
         public static void main(String[] str){
              com.incors.plaf.alloy.AlloyLookAndFeel.setProperty("alloy.licenseCode", "2005/05/28#[email protected]#1v2pej6#1986ew");
              try {
                javax.swing.LookAndFeel alloyLnF = new com.incors.plaf.alloy.AlloyLookAndFeel();
                javax.swing.UIManager.setLookAndFeel(alloyLnF);
              } catch (javax.swing.UnsupportedLookAndFeelException ex) {
              ex.printStackTrace();
              Item_Details ID = new Item_Details();
              ID.setVisible(true);
    public ArrayList getRowData()
         ArrayList rowData=new ArrayList();
         Hashtable item = new Hashtable();
         item.put(new Long(0),new String("Item No:aaaaaaa aaaaaaaa aaaaaaaaa aaaaaa"));
         item.put(new Long(1),new String("RED-1050"));
         rowData.add(0,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Description:rt r trtrt rttrytrr tytry trytry tr tr rty thyjyhjhnhnhgg hhjhgjh"));
         item.put(new Long(1),new String("SYSTEM 18 mbh COOLING 13 mbh HEATING 230/208 v POWER AIRE "));
         rowData.add(1,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Stage:"));
         item.put(new Long(1),new String("Draft"));
         rowData.add(2,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Price: "));
         item.put(new Long(1),new String("999.00"));
         rowData.add(3,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(4,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(5,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(6,item);
         /*item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(5,item);
         item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(6,item);
         item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(7,item);
         return rowData;
    public String[] getColData()
         String[] colData = new String[]{"Attribute","Value"};
         return colData;
    public ArrayList getRowData1()throws MalformedURLException{
         ArrayList rowData = new ArrayList();
         Hashtable item = new Hashtable();
         String str = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
         URL url = new URL(str);
         ImageIcon ic = new ImageIcon(url);
         ImageIcon scaledImage = new ImageIcon(ic.getImage().getScaledInstance(getImageHeight(), -1,Image.SCALE_SMOOTH));
         item.put(new Long(0), scaledImage);
         rowData.add(0,item);
         String str1 = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
         URL url1 = new URL(str1);
         ImageIcon ic1 = new ImageIcon(url1);
         ImageIcon scaledImage1 = new ImageIcon(ic1.getImage().getScaledInstance(120, -1,Image.SCALE_DEFAULT));
         item.put(new Long(0),scaledImage1);
         rowData.add(1,item);
         return rowData;
    public String[] getColumns1(){
         String[] colData = new String[]{"Image"}; 
         return colData;
    public int getImageHeight(){
         ImageIcon ic = new ImageIcon("c:\\image\\ImageNotFound.gif");
         return ic.getIconHeight();
    class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
         public TextAreaCellRenderer() {
              setEditable(false);
              setLineWrap(true);
              setWrapStyleWord(true);
         public Component getTableCellRendererComponent(JTable table,
              Object value, boolean isSelected, boolean hasFocus,
              int nRow, int nCol)
              if (value instanceof String)
                   setText((String)value);
              // Adjust row's height
              int width = table.getColumnModel().getColumn(nCol).getWidth();
              setSize(width, 1000);
              int rowHeight = getPreferredSize().height;
              if (table.getRowHeight(nRow) != rowHeight)
                   table.setRowHeight(nRow, rowHeight);
              this.setBackground(Color.WHITE);
              return this;

    I think Problem is between these code only
    for(int k=0;k<columnCount;k++)
                   TableCellRenderer renderer = null;
                   TableCellEditor editor = null;
                   renderer = new TextAreaCellRenderer();
                                                                itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);or in this renderer
    class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
         public TextAreaCellRenderer() {
              setEditable(false);
              setLineWrap(true);
              setWrapStyleWord(true);
         public Component getTableCellRendererComponent(JTable table,
              Object value, boolean isSelected, boolean hasFocus,
              int nRow, int nCol)
              if (value instanceof String)
                   setText((String)value);
              // Adjust row's height
              int width = table.getColumnModel().getColumn(nCol).getWidth();
              setSize(width, 1000);
              int rowHeight = getPreferredSize().height;
              if (table.getRowHeight(nRow) != rowHeight)
                   table.setRowHeight(nRow, rowHeight);
              this.setBackground(Color.WHITE);
              return this;
    }

  • How can i add a MouseMotionlistener  to the cells in the JTable?

    hi !
    how can i add a MouseMotionlistener to the cells in the JTable?

    yes i have.but that is different from adding MouseMotionlistener to the cells for me .
    i just want get the values where the mouse moves to .

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

  • Custom JTable cell editor problem

    I have a custom JTable cell editor which is a JPanel with 2 JtextFields, One for a name, the other for a data value. My problem lies in when the the cell is selected and then the user start typing. The JTextfield outline shows up, but there is no carat. I can only edit the cell when I click the mouse in it again. I have my isCellEditable method set to only allow editing on 2 mouse clicks, but I did try it with just returning true and had the same problem. Please help.
    Code:
    class cellValue {
    String name;
    String data;
    Color nameColor;
    Color dataColor;
    Font font;
    public cellValue(String n, String d, Color nC, Color dC, Font ff){
    name = n;
    data = d;
    nameColor = nC;
    dataColor = dC;
    font = ff;
    } //end class
    public class TextFieldCellEditor extends JPanel implements TableCellRenderer, TableCellEditor{
    private EventListenerList listenerList = new EventListenerList();
    private ChangeEvent event = new ChangeEvent(this);
    private cellValue s;
    private int e_row=0;
    private int e_col=0;
    private JTextField ta;
    private JTextField tb;
    public TextFieldCellEditor() {
    setLayout(new GridBagLayout());
    ta = new JTextField();
    tb = new JTextField();
    tb.setHorizontalAlignment(SwingConstants.RIGHT);
    add(ta, new GridBagConstraints(0,0,1,1,0.6,0.0,java.awt.GridBagConstraints.WEST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    add(new JLabel(" "),new GridBagConstraints(1,0,1,1,0.1,0.0,java.awt.GridBagConstraints.WEST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    add(tb, new GridBagConstraints(2,0,1,1,0.3,0.0,java.awt.GridBagConstraints.EAST,java.awt.GridBagConstraints.BOTH,new Insets(0,1,0,0),0,0));
    } //end init
    public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected,
    boolean hasFocus,int row, int column) {
    s = (cellValue)value;
    e_row = row;
    e_col = column;
    ta.setText(s.name);
    tb.setText(s.data);
    ta.setFont(s.font);
    tb.setFont(s.font);
    ta.setForeground(s.nameColor);
    tb.setForeground(s.dataColor);
    setForeground(table.getForeground());
    setBackground(table.getBackground());
    ta.setBackground(table.getBackground());
    tb.setBackground(table.getBackground());
    ta.setCaretColor(Color.WHITE);
    tb.setCaretColor(Color.WHITE);
    return (JComponent)(this);
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    return (getTableCellRendererComponent(table, value,isSelected, true, row, column));
    public boolean isCellEditable(EventObject e) {
    if (e instanceof MouseEvent) {
    return ((MouseEvent)e).getClickCount() >= 2;
    } return true;
    // return true;
    public boolean shouldSelectCell(EventObject anEvent) {
    return (true);
    public void cancelCellEditing() {
    public boolean stopCellEditing() {
    fireEditingStopped();
    return (true);
    public Object getCellEditorValue() {
    return (ta.getText());
    public void addCellEditorListener(CellEditorListener l){
    try {
    SwingUtilities.invokeLater(
    new Runnable() {
    public void run() {requestFocus();}
    } catch (Exception e) {};
    listenerList.add(CellEditorListener.class, l);
    public void removeCellEditorListener(CellEditorListener l) {
    listenerList.remove(CellEditorListener.class, l);
    protected void fireEditingStopped(){
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2)
    ((CellEditorListener)listeners[i+1]).editingStopped(event);
    protected void fireEditingCanceled() {
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2)
    ((CellEditorListener)listeners[i+1]).editingCanceled(event);
    } //end class

    Thanks again for the repley.
    I tried removing the celleditorlistener and using the setSurrenderFocusOnKeystroke, but it did not work. The textfield is editable;
    I did change:
    public void addCellEditorListener(CellEditorListener l){
    try {
    SwingUtilities.invokeLater(
    new Runnable() {
    public void run() {ta.requestFocus();}
    } catch (Exception e) {};
    listenerList.add(CellEditorListener.class, l);
    }This allows the first textfield to request focus and this seems to work. But when I highlight a cell, then start typing, the first character I type puts me into the editor, but it is lost. Example:
    I type hello
    and get ello in the cell. Then when I press enter the input is excepted and the selection goes to the next cell, but I cannot move the Highlight cursor at all, seems locked. The only way I can continue to the next cell is to use the mouse.
    You said you had a cell editor working. Would you care to share as an example. This is killing me to get this to work properly.
    Thanks again
    Dave

  • How to write an element in a  JTable Cell

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

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

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

  • Update jtable cell via numeric keypad

    Hi,
    I have a problem, trying to figure out how to input numbers in a jtextfield in a jtable cell, from a group of jbuttons (rendered as a numeric keypad). I can get the cell to focus, but when I click on one of the jbuttons in the keypad, the cell loses focus and nothing is printed. I can update the cell by directly typing from the keyboard; that works fine. But I'm lost when trying to do it from the touch-screen keypad. Can anyone point me in the right direction. I assume I need to attach additional listeners somewhere.
    Thanks in-advance.
    Lee

    I can get the cell to focus, Then the code for you button would need to be something like:
    String text = (String)table.getValueAt(...);
    String updated = text + button.getText();
    table.setValueAt(updated, ...);

  • Update JTable cells via setValueAt

    Hello all,
    I'm trying to implement a setValueAt method using an arrayList.....no success.What listeners should I have set up(For JTable or my table model)? I am new at this and I'm trying to update the JTable cells after a query from some db. Could anyone help?
    When trying to change the a value in the table I get these errors:
    "Exception occurred during event dispatching:
    java.lang.ClassCastException: java.lang.String
    at CachingResultSetTableModel.getValueAt(CachingResultSetTableModel.java:37)
    at javax.swing.JTable.getValueAt(JTable.java:1711)
    at javax.swing.JTable.prepareRenderer(JTable.java:3530)"
    public void setValueAt(Object avalue, int r, int c){
    if(r < cache.size()){
    row[c] = (Object[])cache.set(r, avalue);
    fireTableCellUpdated(r, c);
    }//setValueAt
    *********For reference here's the getValueAt method*************************
    public Object getValueAt(int r, int c){
    if(r < cache.size()){
    row = (Object[])cache.get(r);
    return row[c];
    else
    return null;
    }//getValueAt

    I would think that everone who starts off with JTable will have a couple of concept problems. I am also going thru this learnig curve. It looks to me ( the blind leading the blind etc) like your basic table has strange data in it. The problem is occuring when the JTable is trying to setup the data from the table model.
    I don't think its anything to do with setValueAt.
    I kept going back to TableMap, TableSorter and JDBCAdaptor examples and copying the code from them to come right.> I debug by putting a System.out .... in all the methods until I get to where the code is giving trouble.
    Good luck [email protected]
    Hello all,
    >
    I'm trying to implement a setValueAt method using an
    arrayList.....no success.What listeners should I have
    set up(For JTable or my table model)? I am new at
    this and I'm trying to update the JTable cells after a
    query from some db. Could anyone help?
    When trying to change the a value in the table I get
    these errors:
    "Exception occurred during event dispatching:
    java.lang.ClassCastException: java.lang.String
    at
    CachingResultSetTableModel.getValueAt(CachingResultSetT
    bIleModel.java:37)
    at javax.swing.JTable.getValueAt(JTable.java:1711)
    at
    javax.swing.JTable.prepareRenderer(JTable.java:3530)"
    public void setValueAt(Object avalue, int r, int c){
    if(r < cache.size()){
    row[c] = (Object[])cache.set(r, avalue);
    fireTableCellUpdated(r, c);
    }//setValueAt
    *********For reference here's the getValueAt
    method*************************
    public Object getValueAt(int r, int c){
    if(r < cache.size()){
    row = (Object[])cache.get(r);
    return row[c];
    else
    return null;
    }//getValueAt

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

  • Can JTable cell acts as JList?

    I was planning to create an Event Calendar view in Monthly. Currently my jTable cell extends JTextArea. My problem is that, for example, today I got 2 events display in one cell, when a user double-click the "today" cell, an edit form will pop out, if there are 2 events in one cell, how I know which events to be edit? In this case I was thinking to use JList instaed of jTextArea. so i can choose which event to be edit. Is there any example showing how to implement jTable with jList cell? or is there any other method to overcome it?

    I haven't used a JList in a JTable so far, but for a JComboBox you find a working example in the tutorial. That may give you some ideas.
    What I did use is a (read only) JTable in a JTable. So if you don't achieve your goal with JList there are alternatives.
    But wait for our table specialists to come along.

  • Custom JTable cell editors and persistence

    I have a JTable with an underlying data model (an extension of AbstractTableModel) that uses custom cell editors in the last column. The cell editor in that column, for a given row, depends on the value selected in another column of the same row. The cell editors include text, date, list, and tree editors (the last one in a separate dialogue). The number of rows is changeable.
    I have need to persist the data for a populated table from time to time, for restoration later on. I've achieved that, such that the data model is recreated, the table appears correct, and the appropriate cell editors activated (by creating new instances of the editors' classes).
    However, my problem is that the (custom) cell editors do not reflect the data in the model when editing mode is begun the first time after restoration. Eg. the text editor is always empty, the list editor shows the first item, and no node is selected in the tree editor.
    If I've restored the model correctly, should the editors properly reflect the underlying data when they are set to editing mode?
    I suspected not, and thus tried to explicitly 'set' the correct values immediately after each editor is recreated ... but to no avail.
    Does anyone have any thoughts, or experience with something similar? I'm happy to supply code.

    You can use html tags within Swing, so I think you can do the following:
    * MyRenderer.java
    * Created on 26 April 2007, 10:27
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package newpackage;
    import java.awt.Component;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.SwingConstants;
    import javax.swing.table.TableCellRenderer;
    * @author CS781RJ
    public class MyRenderer extends JLabel implements TableCellRenderer
        public MyRenderer()
            setHorizontalTextPosition(SwingConstants.RIGHT);
            setIconTextGap(3);
            setOpaque(true);
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean cellHasFocus, int row, int column)
            if (isSelected)
                setBackground(table.getSelectionBackground());
                setForeground(table.getSelectionForeground());
            else
                setBackground(table.getBackground());
                setForeground(table.getForeground());
            if (value instanceof String)
                if ((value != null) && (value.toString().length() > 0))
                    System.out.println("Value: " + value.toString());
                    setFont(new java.awt.Font("Tahoma", 0, 11));
                    setText("<html>" + value.toString().replaceAll("\n", "<br>") + "</html>");
            return this;
    }In the class that has the JTable, use the code AFTER declaring the values, columns, etc:
    jTable1.getColumnModel().getColumn(0).setCellRenderer(new MyRenderer());
    jTable1.setValueAt("Riz\nJavaid", 0, 0);One thing I haven't done is to resize the cell heights, make sure this is done.
    Hope this helps
    Riz

  • How to make Jtable cell empty onClick?

    Hi All,
    I have one requirement where I need to make the Jtable cell value empty on click or tab event. So, User does not have to do back space and delete whole string to edit that cell.
    Any idea?
    Thanks in advance.

    Hi camickr,
    Thanks for that reply. It did not work for me but Here is the thing.
    My requirement was : Client does not want to do back space in order do edit cell value when that cell clicked.
    I tried find the solution that, i can make that cell area as selected when it is clicked. my problem is solved. So, I tried to use Table select all editor.
    But here is what i found ......
    If I want that cell area selected, I need to do one more click(3 clicks at the same time) to select the value of that cell & I can put my new value without doing back space(stupid client requirement)
    Thanks for your help

  • Start or stop edit jtable cell editing

    Hello,
    I got a problem with the jtable DefaultModel isCellEditable.
    If I set the IsCellEditable to false, I would not be able to enable the cell selection as and when I want it.
    What I have in mind is the add a mouselister so that if the user select a row using fast left mouse click like the procedure shown below
    private class MouseClickHandler extends MouseAdapter {
    public void mouseClicked(MouseEvent event) {
    int no_mouseclick = 0;
    no_mouseclick = event.getClickCount();
    if (no_mouseclick >= 2) {
    int cur_row = 0;
    cur_row = table.getSelectedRow();
    // table.setColumnSelectionAllowed(true);
    // table.setRowSelectionAllowed(true);
    for (int i=0;i<table.getColumnCount();i++){
    table.editCellAt(cur_row,i);
    System.out.println("mouse row--->" + cur_row);
    I could overwrite the IsCellEditable to true to enable that particular or cell contains in that row to be able to accept input and overwrite any data which in my case obtained from the Sql database a sort of like input module using tabulation . I am also thinking of using text component or combobox to display the value for user selection , but I do not know how to enable a particular cell for editing if the Jtable created is using a non-editable DefaultModel. If I set the IsCellEditable to true, every single cell would be enable for editing , and this defeat the purpose of enable user input only upon double mouseclicks.
    By the way , I am interested to know how to track the data changes in the cell within the jtable so that only those have been modified are notify from the Table model and updated into the Sql table
    Could anyone of you out there provide some hints please
    Thanks

    Hello,
    Tablemodellistener could detect the changes in the data, how about the backend database updating and transactional activity that must be associated with the data changes?
    What is on my mind is that , the moment there is changes in the data detected by the TableModellistener, whatever records associated with or brougt up by Jtable would be all deleted from the database and then follow by the new set of new records to be inserted into the database. The disadvantage of this method is that everytime the backend database connection and activity need to be executed the moment there is a change in the data in the jtable cell. For example the user may be just amendment to only one cell , but all the records associated need to be deleted and then inserted again.
    Perhaps there are better solution to deal with Jtable and JDBC backend connection where in this case, I am using JDO to undertake the database activity like the observable modelling .
    Could someone provide the hint please
    Thank

Maybe you are looking for