1

我有一个JList,它连接到一个 custom DefaultListModel,我想在组件的某些值上更改鼠标光标(取决于项目/值的类型)。在某些项目上它应该是默认光标,在其他一些项目上是手形光标。

我以为我可以在我的自定义中做到这一点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;
}

我的方法不起作用。任何建议如何以正确的方式做到这一点?

4

1 回答 1

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 );
}
于 2012-09-24T15:57:06.350 回答