Forum Stats

  • 3,757,130 Users
  • 2,251,200 Discussions
  • 7,869,736 Comments

Discussions

Highlight JTable rows on rollover

843804
843804 Member Posts: 45,751
edited Jun 29, 2005 8:35PM in Swing
Hi,
I am trying to highlight JTable rows on mouse rollover.. Currently what I do is
 
table.addMouseMotionListener (new MouseMotionListener() {
public void mouseMoved (MouseEvent me) {
   int row = table.getRowAtPoint(me.getx(),me.gety());
   if (row >=0)
         changeSelection (row, 0, false, false);
}
public void mouseDragged(MouseEvent me) {}
}
 
As obvious from the "changeSelection" this actually changes the selection. The required behavior should be that rows get highlighted on rollover, but that doesn't change the actual selection..
From what I understand, I could use cell renderers, but not sure how exactly..
Any suggestions welcome!

Comments

  • 843804
    843804 Member Posts: 45,751
    Here is a simple example that might give some ideas:
    import java.awt.Component;
    import java.awt.event.MouseEvent;
    
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    import javax.swing.table.*;
    
    public class RollOverTable extends JTable {
    
        private int rollOverRowIndex = -1;
        
        public RollOverTable(TableModel model) {
            super(model);
            RollOverListener lst = new RollOverListener();
            addMouseMotionListener(lst);
            addMouseListener(lst);
        }
        
        public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            Component c = super.prepareRenderer(renderer, row, column);
            if( isRowSelected(row) || (row == rollOverRowIndex) ) {
                c.setForeground(getSelectionForeground());
                c.setBackground(getSelectionBackground());
            }
            else {
                c.setForeground(getForeground());
                c.setBackground(getBackground());
            }
            return c;
        }
        
    
        private class RollOverListener extends MouseInputAdapter {
    
            public void mouseExited(MouseEvent e) {
                rollOverRowIndex = -1;
                repaint();
            }
    
            public void mouseMoved(MouseEvent e) {
                int row = rowAtPoint(e.getPoint());
                if( row != rollOverRowIndex ) {
                    rollOverRowIndex = row;
                    repaint();
                }
            }
        }
    }
  • 843804
    843804 Member Posts: 45,751
    Thanks for the quick reply! that worked real fine..
  • 843804
    843804 Member Posts: 45,751
    Thanks for the quick reply! that worked real fine..
    You are welcome.
This discussion has been closed.