2012-09-24 47 views
1

我有一個JList,它連接到自定義DefaultListModel,我想在組件的某些值上更改鼠標光標(取決於項目/值的類型)。在某些項目上,它應該是默認的光標,在其他某個手形光標上。將光標更改爲單個JList值

我認爲我可以在我的自定義DefaultListCellRenderer做到這一點:

@Override 
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { 
    super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); 

    MyItem item = (MyItem) value; 
    setText(item.getDisplay()); 

    if (!item.getType().equals("i")) 
     setCursor(new Cursor(Cursor.HAND_CURSOR)); // <-- doesn’t work 

    return this; 
} 

我的做法是行不通的。任何建議如何以正確的方式做到這一點?

回答

2

您必須在定位某個單元格時手動更新遊標。這裏有一個小例子:

public static void main (String[] args) 
{ 
    final JFrame frame = new JFrame(); 

    final JList list = new JList (
      new Object[]{ Cursor.DEFAULT_CURSOR, Cursor.CROSSHAIR_CURSOR, Cursor.TEXT_CURSOR, 
        Cursor.WAIT_CURSOR, Cursor.SW_RESIZE_CURSOR, Cursor.SE_RESIZE_CURSOR, 
        Cursor.NW_RESIZE_CURSOR, Cursor.NE_RESIZE_CURSOR, Cursor.N_RESIZE_CURSOR, 
        Cursor.S_RESIZE_CURSOR, Cursor.W_RESIZE_CURSOR, Cursor.E_RESIZE_CURSOR, 
        Cursor.HAND_CURSOR, Cursor.MOVE_CURSOR }); 

    list.setCellRenderer (new DefaultListCellRenderer() 
    { 
     public Component getListCellRendererComponent (JList list, Object value, int index, 
                 boolean isSelected, 
                 boolean cellHasFocus) 
     { 
      JLabel label = (JLabel) super 
        .getListCellRendererComponent (list, value, index, isSelected, 
          cellHasFocus); 
      label.setText ("Cursor constant: " + value); 
      return label; 
     } 
    }); 

    list.addMouseMotionListener (new MouseMotionListener() 
    { 
     public void mouseDragged (MouseEvent e) 
     { 
      updateCursor (e); 
     } 

     public void mouseMoved (MouseEvent e) 
     { 
      updateCursor (e); 
     } 

     private void updateCursor (MouseEvent e) 
     { 
      int cursor = (Integer) list.getModel() 
        .getElementAt (list.locationToIndex (e.getPoint())); 
      list.setCursor (Cursor.getPredefinedCursor (cursor)); 
     } 
    }); 

    frame.add (list); 

    frame.pack(); 
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); 
    frame.setLocationRelativeTo (null); 
    frame.setVisible (true); 
} 
+0

非常感謝。很棒。 – laserbrain

+1

+1,請考慮將此UI初始化代碼移至SwingUtilities.invokeLater塊 –

+0

@GuillaumePolet即使在EDT之外,像mine這樣的小示例也將始終保持穩定。 –