In my application, I\'d like to create a rollover effect with the rows of a JTable. For example, when the mouse enters the row, the background color of that row will change; co
Use the below code, which will give you an idea about applying rollover effect with rows of a JTable.
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();
}
}
}
}