Change JList item background color on hover

时光总嘲笑我的痴心妄想 提交于 2019-12-07 02:33:24
MadProgrammer

I, personally, would use a MouseMotionListener over overriding the processMouseMotionEvent, but that's just me.

You need some way to tell the renderer which rows are "highlighted", the two immediate ways I can think of achieving this is to ...

  1. Create a custom JList which has methods to set/get the highlighted row. You would then need to cast to this implementation and interrogate the appropriate method, taking action as required.
  2. Provide a method within the list data that mark the row as highlighted or not. This would allow you to interrogate the data directly.

The advantage of the first approach is that it isolates the responsibility to the view, where it really belongs. It does have the disadvantage of meaning you need to create a custom JList. It might be easier to use the getClientProperty and putClientProperty methods instead, this would mean you wouldn't need a custom implementation nor cast the list in the renderer, but is has the disadvantage of not being obvious to other developers.

The second approach mixes display and data information together, not something I would encourage as you really want to keep this kind of stuff separated ;)

Here's how I did it (solution here: http://objectmix.com/java/73071-highlight-itemin-jlist-mouseenter-mouse-over.html, second message):

private int mHoveredJListIndex = -1;

...

mList.addMouseMotionListener(new MouseAdapter() {
  public void mouseMoved(MouseEvent me) {
    Point p = new Point(me.getX(),me.getY());
    int index = mList.locationToIndex(p);
    if (index != mHoveredJListIndex) {
      mHoveredJListIndex = index;
      mList.repaint();
    }
  }
});

And in your renderer:

public class CellRenderer extends JComponent implements ListCellRenderer
{

  @Override
  public Component getListCellRendererComponent(JList aList, Object aValue, int aIndex, boolean aIsSelected, boolean aCellHasFocus)
  {
    Color backgroundColor = mHoveredJListIndex == aIndex ? Color.gray : Color.white;
    JPanel pane = new JPanel(new BorderLayout()); // add contents here   

    pane.setBackground(backgroundColor);
    return pane;
  }
}
mKorbel

AFAIK good RolloverSupportTest / Hightlighter is implemented

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!