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();        frame.show();    }    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(Color.red);          this.setForeground(Color.blue);       }       else       {          this.setBackground(Color.cyan);          this.setForeground(Color.darkGray);       }        String aStr = "Row " + row+ "Column"+column;        this.setText(aStr);    return this;  }
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: