如何更改光标类型

时间:2010-03-28 22:56:11

标签: java image grid cursor

此问题与之前的帖子有关。 How to save file and read

alt text http://freeimagehosting.net/image.php?dc73c3bb33.jpg

只有当鼠标指向不是Null(包含图像)的网格时,如何才能将光标更改为“Hand”?

到目前为止,光标在整个网格上变为“手”(null或非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 个答案:

答案 0 :(得分: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:解决了小问题。

答案 1 :(得分:3)

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

if(tblExamHistoryAll.columnAtPoint(evt.getPoint()) == 5)
{
     setCursor(Cursor.HAND_CURSOR);
}
else
{
     setCursor(0);
}