JTextAreaの行をマウスでロールオーバー表示
Total: 9716
, Today: 3
, Yesterday: 2
Posted by aterai at
Last-modified:
概要
JTextArea
のマウスカーソルがある行をロールオーバー表示します。
Screenshot
Advertisement
サンプルコード
class HighlightCursorTextArea extends JTextArea {
private static final Color LINE_COLOR = new Color(250, 250, 220);
private int rollOverRowIndex = -1;
private MouseAdapter rolloverHandler;
@Override public void updateUI() {
removeMouseMotionListener(rolloverHandler);
removeMouseListener(rolloverHandler);
super.updateUI();
setOpaque(false);
setBackground(new Color(0x0, true)); // Nimbus
rolloverHandler = new RollOverListener();
addMouseMotionListener(rolloverHandler);
addMouseListener(rolloverHandler);
}
@Override protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
Insets i = getInsets();
int h = g2.getFontMetrics().getHeight();
int y = rollOverRowIndex * h + i.top;
g2.setPaint(LINE_COLOR);
g2.fillRect(i.left, y, getSize().width - i.left - i.right, h);
g2.dispose();
super.paintComponent(g);
}
private class RollOverListener extends MouseAdapter {
@Override public void mouseExited(MouseEvent e) {
rollOverRowIndex = -1;
repaint();
}
@Override public void mouseMoved(MouseEvent e) {
int row = getLineAtPoint(e.getPoint());
if (row != rollOverRowIndex) {
rollOverRowIndex = row;
repaint();
}
}
public int getLineAtPoint(Point pt) {
Element root = getDocument().getDefaultRootElement();
return root.getElementIndex(viewToModel(pt));
}
}
}
View in GitHub: Java, Kotlin解説
MouseAdapter
を継承したRollOverListener
でマウスカーソルのある行を記憶JTextArea#paintComponent
メソッドをオーバーライドしてその行の背景色を変更