目前,我有Jlist
一个自定义CellRenderer
如下。我附加了一个自定义MouseListener
以捕获悬停事件,然后是双击事件;但是当我以这种方式添加它们时,事件并没有被触发。20 分钟后,我发现这是因为JList
阻止了事件到达各个列表项。有什么方法可以强制将JList
鼠标事件转发给它的子元素,或者有更好的方法来做到这一点。
我的细胞渲染器:
public class FriendRenderer extends DefaultListCellRenderer {
private static final long serialVersionUID = 1L;
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean hasFocus) {
Friend friend = (Friend)value;
JLabel label = new JLabel(friend.getName());
JPanel mainOuterPanel = new JPanel();
mainOuterPanel.setLayout(new BorderLayout());
/* Adding components to mainOuterPanel... */
/* Here is where I add the custom MouseListener */
mainOuterPanel.addMouseListener(new ListItemMouseListener());
return(mainOuterPanel);
}
}
我的鼠标监听器:
public class ListItemMouseListener implements MouseListener{
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {
Component source = e.getComponent();
source.setBackground(new Color(102, 99, 86));
System.out.println("Mouse entered on " + source.toString());
}
@Override
public void mouseExited(MouseEvent e) {
Component source = e.getComponent();
source.setBackground(null);
System.out.println("Mouse Exited on " + source.toString());
}
}
我在 JFrame 中构建 JList 的位置:
private JList getFriendsList(){
friendsList = new JList(getFriendsListModel()); //TODO Actually fill with data
friendsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
friendsList.setLayoutOrientation( JList.VERTICAL );
friendsList.addListSelectionListener(new FriendsListSelectionListener());
friendsList.setCellRenderer(new FriendRenderer());
return friendsList;
}
提前致谢!