Child: [r10] (diff)

Download this file

NumberedEditorKit.java    95 lines (85 with data), 2.9 kB

 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
92
93
94
/**
* @author Stanislav Lapitsky
* @version 1.0
*
* Adapted by Nuno Brito in 2013-09-18 from:
* http://www.developer.com/java/other/article.php/3318421/Add-Line-Numbering-in-the-JEditorPane.htm
*/
package GUI;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.text.*;
public class NumberedEditorKit extends StyledEditorKit {
@Override
public ViewFactory getViewFactory() {
return new NumberedViewFactory();
}
}
class NumberedViewFactory implements ViewFactory {
@Override
public View create(Element elem) {
String kind = elem.getName();
if (kind != null)
if (kind.equals(AbstractDocument.ContentElementName)) {
return new LabelView(elem);
}
else if (kind.equals(AbstractDocument.
ParagraphElementName)) {
// return new ParagraphView(elem);
return new NumberedParagraphView(elem);
}
else if (kind.equals(AbstractDocument.
SectionElementName)) {
return new BoxView(elem, View.Y_AXIS);
}
else if (kind.equals(StyleConstants.
ComponentElementName)) {
return new ComponentView(elem);
}
else if (kind.equals(StyleConstants.IconElementName)) {
return new IconView(elem);
}
// default to text display
return new LabelView(elem);
}
}
final class NumberedParagraphView extends ParagraphView {
public static short NUMBERS_WIDTH=42;
public NumberedParagraphView(Element e) {
super(e);
short top = 0;
short left = 0;
short bottom = 0;
short right = 0;
this.setInsets(top, left, bottom, right);
}
@Override
protected void setInsets(short top, short left, short bottom,
short right) {super.setInsets
(top,(short)(left+NUMBERS_WIDTH),
bottom,right);
}
@Override
public void paintChild(Graphics g, Rectangle r, int n) {
super.paintChild(g, r, n);
int previousLineCount = getPreviousLineCount();
int numberX = r.x - getLeftInset();
int numberY = r.y + r.height - 5;
g.drawString(Integer.toString(previousLineCount + n + 1),
numberX, numberY);
}
public int getPreviousLineCount() {
int lineCount = 0;
View parent = this.getParent();
int count = parent.getViewCount();
for (int i = 0; i < count; i++) {
if (parent.getView(i) == this) {
break;
}
else {
lineCount += parent.getView(i).getViewCount();
}
}
return lineCount;
}
}