Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Advanced
Sep 9, 2003

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, new
AttributiveCellRenderer());
        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 //extends
MouseAdapter
    {

        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  implements
TableCellRenderer {

  public AttributiveCellRenderer() {
    setOpaque(true);
  }

  public Component getTableCellRendererComponent(JTable table, Object
value,
                 boolean isSelected, boolean hasFocus, int row, int
column) {
       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;
  }
Jayesh Deshmukh
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date