Change the Cell Color of a JTable on MouseOver

Change the Cell Color of a JTable on MouseOver

This code highlights the cell of a JTable when the cell is moused over. It includes its own Table cell renderer and a Mouse motion listener, for getting the mouse position on the JTable.

public class MouseHoverTable extends JFrame{    int itsRow =0;    int itsColumn = 0;    JTable itsTable;    MouseHoverTable(String framename)    {        super(framename);       itsTable = new JTable( 5, 3 );        //make the table transparent        itsTable.setOpaque(false);        itsTable.setDefaultRenderer(Object.class, newAttributiveCellRenderer());        MyMouseAdapter aMouseAda = new MyMouseAdapter();        itsTable.addMouseMotionListener(aMouseAda);        JScrollPane jsp = new JScrollPane(itsTable);        this.getContentPane().add(itsTable);//jsp);    }public static void main(String[] args){    JFrame frame = new MouseHoverTable("Table Example");    frame.addWindowListener( new WindowAdapter()    {    public void windowClosing(WindowEvent e)    {    Window w = e.getWindow();    w.setVisible(false);    w.dispose();    System.exit(0);    }    } );        frame.pack();;    }    public class    MyMouseAdapter extends MouseMotionAdapter //extendsMouseAdapter    {        public void mouseMoved(MouseEvent e)        {            JTable aTable =  (JTable)e.getSource();            itsRow = aTable.rowAtPoint(e.getPoint());            itsColumn = aTable.columnAtPoint(e.getPoint());            aTable.repaint();        }    }    public class AttributiveCellRenderer extends JLabel  implementsTableCellRenderer {  public AttributiveCellRenderer() {    setOpaque(true);  }  public Component getTableCellRendererComponent(JTable table, Objectvalue,                 boolean isSelected, boolean hasFocus, int row, intcolumn) {       if(row == itsRow && column == itsColumn)       {          this.setBackground(;          this.setForeground(;       }       else       {          this.setBackground(Color.cyan);          this.setForeground(Color.darkGray);       }        String aStr = "Row " + row+ "Column"+column;        this.setText(aStr);    return this;  }
See also  5 Ways to Improve Customer Experience

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist