下面列出了怎么用javax.swing.text.DefaultHighlighter.DefaultHighlightPainter的API类实例代码及写法,或者点击链接到github查看源代码。
private MainPanel() {
super(new BorderLayout());
int maskRange = 2;
HighlightPainter highlightPainter = new DefaultHighlightPainter(Color.GRAY);
JTextArea textArea = new JTextArea();
textArea.setText("aaaaaaaasdfasdfasdfasdf\nasdfasdfasdfasdfasdfasdf\n1234567890\naaaaaaaaaaaaaaaaaasdfasd");
((AbstractDocument) textArea.getDocument()).setDocumentFilter(new NonEditableLineDocumentFilter(maskRange));
try {
Highlighter hilite = textArea.getHighlighter();
Document doc = textArea.getDocument();
Element root = doc.getDefaultRootElement();
for (int i = 0; i < maskRange; i++) { // root.getElementCount(); i++) {
Element elem = root.getElement(i);
hilite.addHighlight(elem.getStartOffset(), elem.getEndOffset() - 1, highlightPainter);
}
} catch (BadLocationException ex) {
// should never happen
RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
wrap.initCause(ex);
throw wrap;
}
add(new JScrollPane(textArea));
setPreferredSize(new Dimension(320, 240));
}
private void reapplyErrorHighlighting() {
getHighlighter().removeAllHighlights();
for (HighlightRun run : highlightRuns) {
try {
getHighlighter().addHighlight(run.start, run.end,
new DefaultHighlightPainter(run.highlight));
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
private MainPanel() {
super(new BorderLayout());
JTextField field1 = new JTextField("0987654321");
field1.setSelectedTextColor(Color.RED);
field1.setSelectionColor(Color.GREEN);
HighlightPainter selectionPainter = new DefaultHighlightPainter(Color.WHITE) {
@Override public Shape paintLayer(Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c, View view) {
Shape s = super.paintLayer(g, offs0, offs1, bounds, c, view);
if (s instanceof Rectangle) {
Rectangle r = (Rectangle) s;
g.setColor(Color.ORANGE);
g.fillRect(r.x, r.y + r.height - 2, r.width, 2);
}
return s;
}
};
Caret caret = new DefaultCaret() {
@Override protected HighlightPainter getSelectionPainter() {
return selectionPainter;
}
};
JTextField field2 = new JTextField("123465789735");
caret.setBlinkRate(field2.getCaret().getBlinkRate());
field2.setSelectedTextColor(Color.RED);
field2.setCaret(caret);
Box box = Box.createVerticalBox();
box.add(makeTitledPanel("Default", new JTextField("12345")));
box.add(Box.createVerticalStrut(10));
box.add(makeTitledPanel("JTextComponent#setSelectionColor(...)", field1));
box.add(Box.createVerticalStrut(10));
box.add(makeTitledPanel("JTextComponent#setCaret(...)", field2));
box.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
add(box, BorderLayout.NORTH);
setPreferredSize(new Dimension(320, 240));
}
/**
* Creates new form GUIWindow
*/
public GUIWindow() {
initComponents();
this.errorHighlighter = new DefaultHighlightPainter(Color.red);
this.fileChooser = new JFileChooser();
this.fileChooser.setFileFilter(new FileNameExtensionFilter("SVG file", "svg", "SVG"));
}