2010-03-28 69 views
4

此問題與上一篇文章相關。 How to save file and read如何更改光標類型

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

我怎樣才能光標變爲「手」,只有當鼠標在網格,其不爲空(含圖片)指出?

到目前爲止,光標變成了所有網格中的「手」(空或非空)。

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

回答

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:修復小問題。

+0

非常感謝克里斯... – Jessy 2010-03-28 23:24:38

+0

我想對「圖像邊框」添加高亮效果,以及使效果更明顯。我怎樣才能做到這一點? – Jessy 2010-03-29 03:09:41

+0

查看更新後的文章:)您可以使用給定的代碼調整您心中的內容。 – 2010-03-29 03:24:22

3

這裏是JTable中的特定列改變光標的一種方法:

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