在我的应用程序中,我想用JTable的行创建过渡效果。例如,当鼠标进入该行时,该行的背景颜色将改变;相反,当鼠标退出该行时,该行的颜色将恢复正常。
我怎样才能做到这一点?
最佳答案
使用下面的代码,这将为您提供关于对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();
}
}
}
}