views:

174

answers:

1

This question is related to the previous post. http://stackoverflow.com/questions/2532936/how-to-save-file-and-read

alt text

How can I change the cursor to "Hand" only when the mouse pointed on grid which is not Null (contained images)?

So far the cursor turn to "Hand" all over the grids (null or not null).

public GUI() {
....
  JPanel pDraw = new JPanel();
  ....
  for(Component component: pDraw.getComponents()){
     JLabel lbl = (JLabel)component;

     //add mouse listener to grid box which contained image
     if (lbl.getIcon() != null)
        lbl.addMouseListener(this);
  }

  public void mouseEntered(MouseEvent e) {
     Cursor cursor = Cursor.getDefaultCursor();
     //change cursor appearance to HAND_CURSOR when the mouse pointed on images
     cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); 
     setCursor(cursor);
  }
+2  A: 

This should have the desired effect:

public GUI() {
  // class attributes
  protected Component entered = null;
  protected Border    defaultB    = BorderFactory...;
  protected Border    highlighted = BorderFactory...;

  ....
  JPanel pDraw = new JPanel();
  ....
  for(Component component: pDraw.getComponents()){
     JLabel lbl = (JLabel)component;

     //add mouse listener to grid box which contained image
     if (lbl.getIcon() != null)
        lbl.addMouseListener(this);
  }

  public void mouseEntered(MouseEvent e) {
     if (!(e.getSource() instanceof Component)) return;
     exit();
     enter((Component)e.getSource());
  }

  public void mouseExited(MouseEvent e) {
     exit();
  }

  public void enter(Component c) {
     //change cursor appearance to HAND_CURSOR when the mouse pointed on images
     Cursor cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); 
     setCursor(cursor);
     c.setBorder(highlighted);
     entered = c;
  }

  public void exit() {
     Cursor cursor = Cursor.getDefaultCursor();
     setCursor(cursor);
     if (entered != null) {
        entered.setBorder(defaultB);
        entered = null;
     }
  }

Edited post for new stuff in comment. BorderFactory javadoc: http://java.sun.com/javase/6/docs/api/javax/swing/BorderFactory.html. Edit 2: fixed small problem.

Chris Dennett
Thank you very much Chris ...
Jessy
I was thinking to add highlight effect on the "image border" as well so that the effect is more visible. How can I do that?
Jessy
Check out the updated post :) You can tweak to your heart's content with the given code.
Chris Dennett
Thanks, it's work but the border stayed there and not removed even the cursor outside the image :-(
Jessy
Fixed a small problem, wasn't setting 'entered'.
Chris Dennett
Thanks .. :-)protected Border defaultB =BorderFactory.createEmptyBorder(); I added this code and it only highlight the image when it within the image ..thank you very much :-)
Jessy
No problem :) Here's a page on borders too: http://java.sun.com/docs/books/tutorial/uiswing/components/border.html
Chris Dennett