我有JList
,它连接到自定义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;
}
我的方法不起作用。有任何建议如何以正确的方式做到这一点?
答案 0 :(得分: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 );
}