4

这个问题与上一篇文章有​​关。 如何保存文件和读取

替代文字 http://freeimagehosting.net/image.php?dc73c3bb33.jpg

仅当鼠标指向非空网格(包含图像)时,如何将光标更改为“手”?

到目前为止,光标在整个网格(null 或 not null)上都变成了“Hand”。

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

2 回答 2

5

这应该具有预期的效果:

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

在评论中编辑了新内容的帖子。BorderFactory javadoc:http: //java.sun.com/javase/6/docs/api/javax/swing/BorderFactory.html。编辑2:修复小问题。

于 2010-03-28T23:11:01.020 回答
3

这是更改 JTable 中特定列的光标的一种方法:

if(tblExamHistoryAll.columnAtPoint(evt.getPoint()) == 5)
{
     setCursor(Cursor.HAND_CURSOR);
}
else
{
     setCursor(0);
}
于 2012-11-24T22:24:43.417 回答