JListのセルをカーソル移動でロールオーバー
Total: 10026
, Today: 1
, Yesterday: 1
Posted by aterai at
Last-modified:
概要
JList
でマウスカーソルの下にあるセルをハイライト表示します。
Screenshot
Advertisement
サンプルコード
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 in GitHub: Java, Kotlin解説
MouseAdapter
をオーバーライドしてマウスカーソルのあるセルを記憶- 記憶したセルの背景色の変更を
JList#repaint(Rectangle)
メソッドで再描画