JTable listener

When data changes in a JTable the event source is the TableModel. So if I use
public void tableChanged(TableModelEvent e)
TableModel source=(TableModel)e.getSource();
I have a pointer to the TableModel which is associated with the table, but not a pointer to the table itself. How can I get a pointer to the table itself? (from inside the listener code)

Why do you need a refernce to the Table itself? The answer to that could determine the answer to the problem.
-Tim

Similar Messages

  • NB6 - jtable listener TableModellistener not found in JTable properties

    According to Swing Java tutorial, a listener TableModelListener must be implemented in order to update JTable entries. I am looking for this listener in NB6 properties for jtable component but can not find it.
    Does anyone knows what is the replacement name for this listener under NB6 or how JTable are updated dynamically.
    Please advice

    You should be looking in the API when you need to lookup other objects and in this case an interface.

  • JTable listener problem,  plz. help  code included

    hi,
    I need help in this JTable. If you run the following code you'll see when you double click in any cell scrollbars will appear if the text is too large for the JTextArea. What I want is when any cell is selected and if the text is too large to fit in the JTextArea I want the scrollbars to appear then. And if I double click in any cell I want some other action to take place. Here is the example code that I got from net and I am trying to play arround with this code. Please run the following code and see what I mean:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.util.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    public class MyMultiRowTableTest extends JFrame
    public MyMultiRowTableTest()
    addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent we)
    System.exit(0);
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(initComponents(), BorderLayout.CENTER);
    protected Container initComponents()
    JPanel mainPanel = new JPanel(new BorderLayout());
    Vector vRows = new Vector();
    Vector vColumns = new Vector();
    vColumns.add("Column1");
    vColumns.add("Column2");
    for (int i=0; i<20; i++)
    Vector vRow = new Vector(2);
    vRow.add(""+(i+1)+". abcdefghijklmnopqrstuvwxyzabcdefghijk" +
    "lmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmno" +
    "pqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstu" +
    "wxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdef" +
    "ghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrs"+
    "tuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghi" +
    "jklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"+
    "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrs"+
    "tuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz");
    vRow.add("asldfjasldfjal�dfjal�jdfal");
    vRows.add(vRow);
    JTable myTable = new JTable(vRows, vColumns);
    for (int i=0; i<myTable.getColumnCount(); i++)
    TableColumn tc = myTable.getColumn(myTable.getColumnName(i));
    if (tc!=null)
    tc.setCellRenderer(new MultiLineCellRenderer());
    tc.setCellEditor(new MultiLineCellEditor());
    myTable.setRowHeight(80);
    mainPanel.add(new JScrollPane(myTable));
    return mainPanel;
    public static void main(String[] args)
    JFrame frame = new MyMultiRowTableTest();
    frame.setSize(800,600);
    frame.setLocation(200,200);
    frame.setVisible(true);
    }//end of the class MyMultiRowTableTest
    class MultiLineCellEditor extends DefaultCellEditor
    protected JTextArea myEditingComponent;
    public MultiLineCellEditor()
    super(new JTextField());
    myEditingComponent = new JTextArea();
    myEditingComponent.setLineWrap(true);
    myEditingComponent.setWrapStyleWord(true);
    myEditingComponent.setOpaque(true);
    myEditingComponent.addKeyListener(new KeyAdapter()
    public void keyPressed(KeyEvent ke)
    if ((ke.getKeyCode()==ke.VK_ENTER) && (ke.getModifiers() == ke.CTRL_MASK))
    stopCellEditing();
    public Object getCellEditorValue()
    return myEditingComponent.getText();
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
    int row, int column)
    Component result = super.getTableCellEditorComponent(table,
    value, isSelected, row, column);
    myEditingComponent.setFont(table.getFont());
    myEditingComponent.setText(""+value);
    if (value instanceof String)
    result = new JScrollPane(myEditingComponent);
    return result ;
    }//end of the class MultiLineCellEditor
    class MultiLineCellRenderer extends JTextArea implements TableCellRenderer
    protected final static Border emptyBorder = BorderFactory.createEmptyBorder(1,2,1,2);
    protected final static Border focusBorder = UIManager.getBorder("Table.focusCellHighlightBorder");
    public MultiLineCellRenderer()
    setLineWrap(true);
    setWrapStyleWord(true);
    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(focusBorder);
    if (table.isCellEditable(row, column))
    setForeground( UIManager.getColor("Table.focusCellForeground") );
    setBackground( UIManager.getColor("Table.focusCellBackground") );
    else
    setBorder(emptyBorder);
    if(value==null)
    myEditingComponent.setText("");
    return new JScrollPane
    (myEditingComponent);
    setText((value == null) ? "" : value.toString());
    return this;
    }//end of the class MultiLineCellRenderer
    If you see when you double click in the first column the scrollbars will appear as the text is too large. But what I need is that when the cell is selected the scrollbars should appear and when I doubleclick in the cell I want some other action to take place. Please help I really don't understand how this cellrenderer and celleditor works. Any help is really appreciated. And thank you in advance.

    hi friend
    i tried to solve your problem , but i couldn't clear myself with program logic u used. but your problem can be solved by trying with the following lines.you need to explore the right place in your logic.
    int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
    int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
    if (value instanceof String)
    result = new JScrollPane(myEditingComponent,v,h);
    return result ;
    in the meanwhile i will try with your code as soon i will get time.
    reply me back if it solves the problem
    bye

  • JTable Listener problem - Urgent Please:)

    How to make listeners detect both change of rows and columns.
    I used ListSelectionListners but that only fires on change of row., How do I detect change of column within the same row?
    Sincerely,

    d

  • JTable cell being edited after model changed.

    I have a fairly simple JTable, with a implementation of AbstractTableModel supplying the data. The cells are edited by using a JComboBox. I wrap these into a DefaultCellEditor. I have a KeyListener attached to the JTable listening for VK_DELETE, and when it finds one, instructs the model to delete the row represented by the selected row in the table.
    Everything works fine until I want to delete a row from the table. My scenario is:
    - I click in a cell, and the editor opens.
    - I select an entry in the list. The editor closes, the result is rendered, and the wee yellow box around the cell is shown
    - I hit the delete key.
    - My key listener picks up the event, and informs the model to delete the row. I remove the row from the model and invoke fireTableDataChanged().
    The result is that the row is deleted, but the table ends up with the cell editor deployed on the cell of the row below (which is now at the same row as the one I just deleted).
    My tracing shows that the isCellEditable is called on the model after the delete. I don't know why.
    Can anyone explain how to prevent this or what might be causing the table to think that the cell needs editing?
    Thanks, Andrew

    It will do whatever is the default. I wrap the JComboBox in a DefaultCellEditor. I can't see how the editor is involved at this point, or why the editor becomes involved after the row has been deleted.
    Remember, at the time that I hit the delete key, there is no editor rendered or visible. I have the JTable displayed, a row selected, and the yellow box around one of the (editable but not currently being edited) cells. This has been achieved by editing a cell (displaying the cell editor - a combo box) and selecting an entry. The editor is removed, and the cell displayed with the (default) cell renderer for the table.
    The delete action is caught by the listener on the table, the model is instructed to delete a row from its underlying data, which fires a fireTableDataChanged event.
    That is all I do. After that it is all swing. The table model starts getting asked about cells being editable after I have finished deleting the row. I'll post the relevant code below if that helps.
    The datamodel is of class ConstraintTableModel (see below) and the column model is of class DefaultTableColumnModel
    JTable table = new JTable( dataModel, columnModel );The column model is defined liike so:
    columnModel = new DefaultTableColumnModel();
    TableColumn labelColumn = new TableColumn(ConstraintTableModel.LABEL_COLUMN);
    labelColumn.setHeaderValue( dataModel.getColumnName(ConstraintTableModel.LABEL_COLUMN));
    labelColumn.setPreferredWidth( 5 );
    labelColumn.setMaxWidth( 5 );
    labelColumn.setResizable( false );
    TableColumn taskColumn = new TableColumn(ConstraintTableModel.TASK_COLUMN);
    taskColumn.setHeaderValue( dataModel.getColumnName(ConstraintTableModel.TASK_COLUMN));
    TableColumn typeColumn = new TableColumn(ConstraintTableModel.TYPE_COLUMN);
    typeColumn.setHeaderValue( dataModel.getColumnName(ConstraintTableModel.TYPE_COLUMN));
    columnModel.addColumn( labelColumn );
    columnModel.addColumn( taskColumn );
    columnModel.addColumn( typeColumn );I add the key listener like so:
    table.addKeyListener( new KeyAdapter()
        public void keyPressed( KeyEvent e )
          if( e.getKeyCode() == KeyEvent.VK_DELETE )
            log.debug("Delete pressed in listener attached to table ");
            JTable t = (JTable) e.getSource();
            int selectedRow = t.getSelectedRow();
            if( selectedRow >= 0 )
              log.debug("  Removing row " + selectedRow);
              ((ConstraintTableModel)t.getModel()).removeRow(selectedRow);
            log.debug("Finished with key press");
      } );The cell editor is created like this:
    JComboBox taskEditorComponent = new JComboBox( tasksModel );
    taskEditorComponent.setFont( GanttChart.tableFont );
    taskEditorComponent.setBackground( Color.WHITE );
    DefaultCellEditor taskEditor = new DefaultCellEditor(taskEditorComponent);
    taskEditor.setClickCountToStart( 1 );
    table.setDefaultEditor( GanttTask.class, taskEditor );The model is coded like so:
    class ConstraintTableModel extends AbstractTableModel
        // Constants
        public static final int LABEL_COLUMN = 0;
        public static final int TASK_COLUMN = 1;
        public static final int TYPE_COLUMN = 2;
        private Vector          columnNames;
        private ArrayList       dataRows;
        public ConstraintTableModel()
            super();
            this.buildDataVector();
            this.addPrimerRow();
         * Every row in the table is a GanttConstraint. Therefore when deciding what to
         * display in any particular column of the table, we need to determine what the
         * column is, and then use the informatino in the GanttConstraint to go out to the
         * lookup and get the relevant object, and value to display.
        public Object getValueAt( int row, int col )
            Object          returnObject = "";
            GanttConstraint aConstraint = (GanttConstraint) this.getDataRows().get( row );
            // We're rendering the task column. If there's no task id (partially filled in row)
            // return blank otherwise return the master task
            else if( col == ConstraintTableModel.TASK_COLUMN )
                if( aConstraint.getMasterId() != null )
                    GanttTask masterTask = (GanttTask) real.getLookup().get( aConstraint.getMasterId() );
                    returnObject = masterTask;
            // We're rendering the type column. If there's no type (partially filled in row)
            // return blank otherwise return the constraint type
            else if( col == ConstraintTableModel.TYPE_COLUMN )
                if( aConstraint.getType() != null )
                    GanttConstraintType constraintType = (GanttConstraintType) GanttConstraintType.getConstraintTypes()
                                                                                                     .get( aConstraint.getType()
                                                                                                                      .intValue() );
                    returnObject = constraintType;
            return returnObject;
         * When we receive this message, we are handed an object of the type specified in
         * getColumnClass. We need to take this object and place the relevant information into
         * the GanttConstraint row in the table model.
         * Depending on whether the row being modified is an existing row or a new row, set
         * the state of the constraint appropriately.
         * @see javax.swing.table.TableModel#setValueAt(java.lang.Object, int, int)
        public void setValueAt( Object value, int row, int col )
            log.debug( "+setValueAt (row/col) " + row + "/" + col );
            if ( value == null )
                log.debug( "  handed a null value. Returning" );
                return;
            GanttConstraint aConstraint = (GanttConstraint) this.getDataRows().get( row );
            // If we are modifying the primer row, add another primer row.
            if( row == ( this.getRowCount() - 1 ) ) // Last row is always the primer
                log.debug( "  adding a primer row" );
                this.addPrimerRow();
            // We're modifying the Task data. Get the GanttTask handed to us and place it
            // into the master slot in the constraint.
            if( col == ConstraintTableModel.TASK_COLUMN ) // Task
                log.debug( "  updating the master task" );
                GanttTask selectedTask = (GanttTask) value;
                aConstraint.setMaster( selectedTask );
            // We're modifying the Type data. Get the GanttConstraintType handed to us and place it
            // into the type slot in the constraint.
            if( col == ConstraintTableModel.TYPE_COLUMN ) // Constraint type
                log.debug( "  updating the constraint type" );
                GanttConstraintType selectedConstraintType = (GanttConstraintType) value;
                aConstraint.setType( selectedConstraintType.getType() );
            log.debug( "-setValueAt" );
        public Class getColumnClass( int col )
            Class columnClass = super.getColumnClass( col );
            if( col == ConstraintTableModel.LABEL_COLUMN )
                columnClass = String.class;
            if( col == ConstraintTableModel.TASK_COLUMN )
                columnClass = GanttTask.class;
            if( col == ConstraintTableModel.TYPE_COLUMN )
                columnClass = GanttConstraintType.class;
            return columnClass;
        // We are handing the data storage
        public void setDataRows( ArrayList dataRows )
            this.dataRows = dataRows;
        public boolean isCellEditable( int row, int col )
            log.debug( "+isCellEditable (row/col) " + row + "/" + col );
            if( !real.canEdit() )
                return false;
            if( ( col == ConstraintTableModel.TASK_COLUMN ) ||
                    ( col == ConstraintTableModel.TYPE_COLUMN ) )
                return true;
            else
                return false;
        // We are handing the data storage
        public ArrayList getDataRows()
            return this.dataRows;
        public String getColumnName( int column )
            return (String) this.getColumnNames().get( column );
         * Clean up rows that do not have both the master task and type set. Not interested in them
        public void removeDirtyRows()
            log.debug( "+removeDirtyRows" );
            Iterator dataIterator = this.getDataRows().iterator();
            while( dataIterator.hasNext() )
                GanttConstraint element = (GanttConstraint) dataIterator.next();
                if( ( element.getMasterId() == null ) || ( element.getType() == null ) )
                    element.setTransient();
                    dataIterator.remove();
            fireTableDataChanged();
            log.debug( "-removeDirtyRows" );
        public void removeRow( int row )
            log.debug( "+removeRow(" + row + ")" );
            if( row < this.getDataRows().size() )
                GanttConstraint aConstraint = (GanttConstraint) this.getDataRows().get( row );
                this.getDataRows().remove( row );
                if( aConstraint.isClone() )
                    aConstraint.setDeleted();
                else
                    aConstraint.setTransient();
                    getClone().removeConstraint( aConstraint );
                fireTableDataChanged();
            if( this.getRowCount() == 0 )
                this.addPrimerRow();
            log.debug( "-removeRow" );
        public void clearRow( int row )
            log.debug( "+clearRow(" + row + ")" );
            if( row < this.getDataRows().size() )
                GanttConstraint aConstraint = (GanttConstraint) this.getDataRows().get( row );
                aConstraint.setMasterId( null );
                aConstraint.setType( null );
                fireTableRowsUpdated( row, row );
            log.debug( "-clearRow" );
        public int getColumnCount()
            return getColumnNames().size();
        public int getRowCount()
            return dataRows.size();
         * The table will be filled with constraints relevant to 'clone'.
        private void buildDataVector()
            ArrayList  data = new ArrayList( 1 );
            Collection allConstraints = getClone().getStartConstraints();
            allConstraints.addAll( getClone().getEndConstraints() );
            Iterator constraintIter = allConstraints.iterator();
            while( constraintIter.hasNext() )
                GanttConstraint element = (GanttConstraint) constraintIter.next();
                if( element.getType().equals( GanttConstraint.START_SPECIFIED ) ||
                        element.getType().equals( GanttConstraint.FINISH_FROM_DURATION ) )
                    continue;
                else
                    data.add( element );
            this.setDataRows( data );
        private Vector getColumnNames()
            if( columnNames == null )
                columnNames = new Vector( 3 );
                columnNames.add( " " ); // Needs space otherwise all the headers disappear
                columnNames.add( "Task" );
                columnNames.add( "Constraint" );
            return columnNames;
        private void addPrimerRow()
            log.debug( "+addPrimerRow" );
            // Create a constraint for the 'clone' task. Set it as transient until validation
            // where we will deal with it if necessary.
            GanttConstraint primer = new GanttConstraint( real.getLookup() );
            primer.setObjectId( chart.getNextUniqueId() );
            primer.setTransient();
            primer.setSlave( getClone() );
            primer.setProject( getClone().getProject() );
            getClone().addConstraint( primer );
            this.getDataRows().add( primer );
            int lastRow = this.getRowCount() - 1;
            fireTableRowsInserted( lastRow, lastRow );
            log.debug( "-addPrimerRow" );

  • JTabel double click event

    Hello,
    Is there a way to let a JTable listen to a double click event? I know that you can easily get the selection by a 1 click, but now I want that when there is double clicked an action happens (in this case a popup with a question).
    For the double click event, I think you best could use the mousePressed event together with the int getClickCount(). Can you put that mousePressedEvent on the ListSelectListener and than count the amount of clicks and if 2 or more you fire an action (popup)?
    Grtz

    Using MouseAdapter is a nicety, because you OVERRIDE only the methods you need. In this case mouseClicked(MouseEvent mouseEvent). You did not have to implement all the methods defined in the http://java.sun.com/j2se/1.5.0/docs/api/java/awt/event/MouseListener.html interface.
    The @override annotation should be there because you have just overridden a method already defined in a super class. The main reason is for compiler checking. It basically marks the method, then if the compiler sees the method does not override anything it will complain (For example someone changed the super classes methods name and you did not realise, in this case the compiler will fail because it no longer overrides anything, and you know you need to fix it...i.e. rename your method to match).
    So it's not imperative you add the annotation but it can save you some anguish.... especially if you deal with alot of third party library's that do not maintain backwards compatibility.
    http://java.sun.com/docs/books/tutorial/java/javaOO/annotations.html
    "@Override—the @Override annotation informs the compiler that the element is meant to override an element declared in a superclass "
    Edited by: rh---gnt on Jan 7, 2010 7:56 AM

  • JComboBox cellEditor behaving oddly

    I have a column in a table represented by a combobox. It can have two values - locked, or unlocked. I have defined a CellEditor class for the column. The problem is you can select an item from the combobox, but it does not update the cell until you click on the combo box again! Can anybody help?
    The following is section of the code form my CellEditor class,
         public Component getTableCellEditorComponent(JTable arg0,Object value,boolean arg2,int arg3,int arg4)
         setSelectedItem(value) ;
              return this ;
         public Object getCellEditorValue()
              if (getSelectedIndex() == 1)
              return new Integer(1) ;
              else return new Integer(0) ;

    JTable listens for actionPerformed by the cell editor, so you got to find a way to fire actionPerformed when the ComboPopup disappears. I think you will have to subclass JComboBox to achieve this. Maybe JComboBox offers an ItemEvent, so you can listen to itemChanged() ...

  • Trying to add a listener to a JComboBox in a JTable

    Hi all.
    I have a little problem which I can't resolve.
    I made a program in which I create a table using a class which extends JTable (but this isn't the point with the problem, I think. It's only for rendering purposes)
    In this table I put various types of items (such as Strings, JButton, JComboBox). I have no problem with the visualization of them, but the problem is with the listener for the combo boxes. I created a listener of my own and registered it in the constructor of the combo box editor, but when I change a value it's never fired. Can someone please help me?
    Here's some code which can help understanding the problem
    Combo box editor:
    public class MyComboBoxEditor extends DefaultCellEditor{
    public MyComboBoxEditor(JTableX _tabellaDiAppartenenza) {
    super(new JComboBox());                  
    (JComboBox)super.editorComponent).addItemListener(new MyItemListener((JComboBox)super.editorComponent));    
    public Component getTableCellEditorComponent(JTable arg0, Object arg1, boolean arg2, int arg3, int arg4) {
    String elementi[]=new String[((JComboBox)arg1).getItemCount()];
    for(int i=0;i<((JComboBox)arg1).getItemCount();i++){
    elementi=(String)((JComboBox)arg1).getItemAt(i);
    super.editorComponent=new JComboBox(elementi);
    return super.getTableCellEditorComponent(arg0, arg1, arg2, arg3, arg4);
    }combo box listener:public class MyItemListener implements ItemListener{
    private JComboBox combo;
    public MyItemListener(JComboBox object){
    combo=object;
    public void itemStateChanged(ItemEvent arg0) {
    int changeEvent = arg0.getStateChange();
    if(changeEvent==ItemEvent.SELECTED){
    Object value=arg0.getItem();
    combo.setSelectedItem(value);
    }table:public class JTableX extends JTable{
    protected MyCellEditorModel myCellEditorModel;
    public JTableX(MyDataModel tm){
    super(tm);
    Object ge = defaultEditorsByColumnClass.get(Boolean.class);
    DefaultCellEditor dce = (DefaultCellEditor)ge;
    dce.setClickCountToStart(0);
    MyButtonEditor mbe = new MyButtonEditor(new JCheckBox("Bottone"), this);
    mbe.setClickCountToStart(0);
    MyComboBoxEditor mcbe = new MyComboBoxEditor(this);
    mcbe.setClickCountToStart(0);
    defaultEditorsByColumnClass.clear();
    Hashtable cellEditors = new Hashtable();
    cellEditors.put(JButton.class, mbe);
    cellEditors.put(JComboBox.class, mcbe);
    cellEditors.put(Boolean.class, dce);
    this.defaultRenderersByColumnClass.put(JButton.class, new MyButtonRenderer());
    this.defaultRenderersByColumnClass.put(JComboBox.class, new MyComboBoxRenderer());
    defaultEditorsByColumnClass.put(Object.class, new MyCellEditorModel1(cellEditors));
    public TableCellEditor getCellEditor(int row, int col){
    if(myCellEditorModel!=null) return myCellEditorModel;
    return super.getCellEditor(row,col);
    public TableCellRenderer getCellRenderer(int row, int column) {
    Object value = getValueAt(row,column);
    if (value !=null) {
    return getDefaultRenderer(value.getClass());
    return super.getCellRenderer(row,column);
    public void setCellEditor(MyCellEditorModel anEditor) {
    myCellEditorModel = anEditor;
    }Hoping the code is enough to understand the problem, I thanks all for watching and reading the post and for the future answeres.
    Bye all.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    super.editorComponent=new JComboBox(elementi);You create a new combo box each call to getTableCellEditComponent() (overriding the one of the constructor), but you aren't adding a ItemListener to it.

  • How to listen to key press in JTable

    I've been trying to listen to key press in JTable,
    However it only works if the cell is double-clicked.
    If the tab button is use or the cell is single-clicked, nothing happens to the listener.
    Anybody can help me???
    Thanks

    table.getColumnModel().addColumnModelListener(new TableColumnModelListener(){
      public void columnAdded(TableColumnModelEvent e){}
      public void columnMarginChanged(ChangeEvent e){}
      public void columnMoved(TableColumnModelEvent e){}
      public void columnRemoved(TableColumnModelEvent e){}
      public void columnSelectionChanged(ListSelectionEvent e){
        // column selection changed
    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
      public void valueChanged(ListSelectionEvent event) {
        // row selection changed
    });rykk

  • How to listen a JTable cell is changed?

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

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

  • Adding mouse listener to the column header of a column in a JTable

    Hi
    I want to add a mouse listener to the column header of the 3rd column in a JTable. I dont find any appropriate method to do this. The code I have written to do this is below. But on using this code, the mouselistener is invoked if I click on any column header. Can anyone please help me to fix this.
    table.getTableHeader().addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    /* some actions */
    }

          table.getTableHeader().addMouseListener(new MouseAdapter(){
               public void mousePressed(MouseEvent me) {
                   int tableColumn  =table.columnAtPoint(me.getPoint());//it returns the column index
            });

  • JTable rows listener

    I have this Jtable in my program. Suppose I want to double-click on a row in the table, and this is supposed to cause a listener to respond depending on which row is clicked. what type of listeners do I need to add to the Jtable?

        myTable.addMouseListener(new MouseAdapter() {
          public void mouseReleased(MouseEvent me) {
         if (me.getClickCount()!=2) return;
         int row = myTable.rowAtPoint(me.getPoint());
         System.out.println("Row="+row);

  • Listener for JTable

    hi all
    i'm using JTable for displaying data retrieved from database. I need to count the no of rows dynamically. ie whenever a row is added/deleted to JTable the rowcounter should be in/decremented. is there any event to do this

    You need to add a table model listener to the JTable. Within the table model listener you can get an event when a row is inserted, deleted or updated,
    Cheers
    Marco
    User Interface Blog
    http://www.user-interface.org

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

  • Mouse motion listener for JTable with JScrollpane

    Hi All,
    I have added mouse motion listener for JTable which is added in JScrollPane. But if i move the mouse, over the vertical/horizontal scroll bars, mouse motion listener doesn't works.
    So it it required to add mousemotionlistener for JTable, JScrollPane, JScrollBar and etc.
    Thanks in advance.
    Regards,
    Tamizhan

    I am having one popup window which shows address information. This window contains JTable with JScrollPane and JButton components to show the details. While showing this information window, if the mouse cursor is over popupwindow, it should show the window otherwise it should hide the window after 30 seconds.
    To achieve this, i have added mouse listener to JPanel, JTable, JButton and JScrollPane. so if the cursor is in any one of the component, it will not hide the window.
    but for this i need to add listener to all the components in the JPanel. For JScrollPane i have to add horizontal, vertical and all the top corner buttons of Scroll bar.
    Is this the only way to do this?

Maybe you are looking for

  • I am getting error 100 with adobe download assistant

    I am getting error 100 when I try to log into adobe download assistant. I am using windows vista , on chrome, and use AVG firewall which I allow all adobe. What can I do trying to install Photoshop cs5 extended.

  • Tune up and upgrade or buy new?

    I have a iBook G4. It is starting to show wear and age. It needs a new battery (doesn't hold any charge)and a new power cord (fraying at the barrel). I have very little memory left and it runs very slow at times. I was thinking of buying a new batter

  • How to Load Infoobject in BI 7.0

    Hi, Steps required to load Infoobject in BI 7.0 Thanks, Madhu.

  • Adobe Flash player black bands prior to 11.7.700.202 and again in 11.7.700.224

    I was having issues at my campus when I scroll content.  The browser alternately covers the text, pictures, and buttons with black bars a few lines too early as I scroll.  The bars are random as to doing this, as sometimes it is black bars followed b

  • Error in ilog Elixir

    Dear all I am getting following error in ilog Elixir Argument count mismatch on mx.graphics::SolidColor/begin(). Expected 3, got 2. at ilog.gauges.rectangular.renderers::RectangularTrackRenderer/updateDisplayList()[/usr/flex /flex1.0/maven2-dev/trunk