1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Shape;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Element;
import javax.swing.text.Highlighter;
import javax.swing.text.JTextComponent;
import javax.swing.text.View;
import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter;
public class LineHighlight extends DefaultHighlightPainter {
private JTextComponent theTextComponent = null;
private Highlighter theHighlighter = null;
private Object theLastHighlight = null;
private static Color defaultColor = new Color(230,245,255);
private boolean active = true;
public LineHighlight(JTextComponent aTextComponent, Color lineHighlightColor) {
super(lineHighlightColor == null ? defaultColor : lineHighlightColor);
if (aTextComponent != null) setTextComponent(aTextComponent);
}
private void setTextComponent(JTextComponent aTextComponent) {
theTextComponent = aTextComponent;
DefaultHighlighter defaultHighlighter = (DefaultHighlighter)theTextComponent.getHighlighter();
defaultHighlighter.setDrawsLayeredHighlights(true);
theHighlighter = defaultHighlighter;
}
@Override
public Shape paintLayer(Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c, View view) {
if (active) {
try {
Rectangle r = c.modelToView(offs0);
r.width = c.getSize().width;
g.setColor(getColor());
g.fillRect(r.x, r.y, r.width, r.height);
//c.repaint(r.x, r.y, r.width, r.height);
return r;
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
return null;
}
public void resetLineHighlight() {
if (theTextComponent != null && active) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (theLastHighlight != null) theHighlighter.removeHighlight(theLastHighlight);
Element root = theTextComponent.getDocument().getDefaultRootElement();
int line = root.getElementIndex(theTextComponent.getCaretPosition());
Element lineElement = root.getElement(line);
int start = lineElement.getStartOffset();
int end = lineElement.getEndOffset();
addHighlight(start, end);
}
});
}
}
private void addHighlight(int offset, int end) {
try {
theLastHighlight = theHighlighter.addHighlight(offset, end, this);
}
catch (BadLocationException ble) {
ble.printStackTrace();
}
}
protected void removeHighlight() {
theHighlighter.removeHighlight(theLastHighlight);
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
theTextComponent.repaint();
}
} |
Partager