How can to create a rollover effect in a JTable?

前端 未结 2 1932
醉酒成梦
醉酒成梦 2021-01-25 13:38

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

2条回答
  •  时光取名叫无心
    2021-01-25 14:28

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

提交回复
热议问题