概要

JListでマウスカーソルの下にあるセルをハイライト表示します。

サンプルコード

class RollOverList<E> extends JList<E> {
  protected static final Color ROLLOVER_BACKGROUND = new Color(0xDC_F0_FF);
  protected transient RollOverListener rollOverListener;
  protected int rollOverRowIndex = -1;

  protected RollOverList(ListModel<E> model) {
    super(model);
  }

  @Override public void updateUI() {
    removeMouseListener(rollOverListener);
    removeMouseMotionListener(rollOverListener);
    setSelectionBackground(null); // Nimbus
    super.updateUI();
    rollOverListener = new RollOverListener();
    addMouseMotionListener(rollOverListener);
    addMouseListener(rollOverListener);
    setCellRenderer(new RollOverCellRenderer());
  }

  private class RollOverCellRenderer implements ListCellRenderer<E> {
    private final ListCellRenderer<? super E> renderer = new DefaultListCellRenderer();

    @Override public Component getListCellRendererComponent(
          JList<? extends E> list, E value, int index,
          boolean isSelected, boolean cellHasFocus) {
      Component c = renderer.getListCellRendererComponent(
          list, value, index, isSelected, cellHasFocus);
      if (index == rollOverRowIndex) {
        c.setBackground(ROLLOVER_BACKGROUND);
        if (isSelected) {
          c.setForeground(Color.BLACK);
        }
        // c.setForeground(getSelectionForeground());
        // c.setBackground(getSelectionBackground());
      }
      return c;
    }
  }

  private class RollOverListener extends MouseAdapter {
    @Override public void mouseExited(MouseEvent e) {
      rollOverRowIndex = -1;
      repaint();
    }

    @Override public void mouseMoved(MouseEvent e) {
      int row = locationToIndex(e.getPoint());
      if (row != rollOverRowIndex) {
        Rectangle rect = getCellBounds(row, row);
        if (rollOverRowIndex >= 0) {
          rect.add(getCellBounds(rollOverRowIndex, rollOverRowIndex));
        }
        rollOverRowIndex = row;
        repaint(rect);
      }
    }
  }
}
view all

解説

上記のサンプルでは、MouseAdapterをオーバーライドしてマウスカーソルのあるセルを記憶し、そのセルの背景色などの変更をJList#repaint(Rectangle)メソッドで再描画しています。

参考リンク

コメント