下面列出了javax.swing.text.DefaultHighlighter.DefaultHighlightPainter#javax.swing.text.Highlighter.HighlightPainter 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void caretUpdate(CaretEvent e) {
int cursor = e.getDot();
JTextPane textPane = (JTextPane)e.getSource();
TokenPositionAnalysis analysis = getAnalysisForCharIndex(cursor);
Highlighter highlighter = textPane.getHighlighter();
HighlightPainter painter = new DefaultHighlightPainter(Color.orange);
try {
highlighter.removeAllHighlights();
if ( analysis!=null ) {
highlighter.addHighlight(analysis.charIndexStart, analysis.charIndexStop+1, painter);
}
scope.injectNLConsole.setText(analysis!=null ? analysis.wsAnalysis : "");
scope.injectNLConsole.setCaretPosition(0);
scope.alignConsole.setText(analysis!=null ? analysis.alignAnalysis : "");
scope.alignConsole.setCaretPosition(0);
}
catch (Exception ex) {
ex.printStackTrace(System.err);
}
}
private int appendText(JTextArea area, String text, boolean highlight) {
int start = area.getDocument().getLength();
if (text == null || text.length() == 0) {
return start;
}
int end = start + text.length();
try {
area.getDocument().insertString(start, text, null);
if (highlight) {
Highlighter hilite = area.getHighlighter();
HighlightPainter painter =
new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
hilite.addHighlight(start, end - 1, painter);
}
} catch (BadLocationException e) {
logger.error(e.getMessage(), e);
}
return end;
}
public static void setHighlight(JTextComponent jtc, String pattern, HighlightPainter painter) {
Highlighter highlighter = jtc.getHighlighter();
highlighter.removeAllHighlights();
Document doc = jtc.getDocument();
try {
String text = doc.getText(0, doc.getLength());
Matcher matcher = Pattern.compile(pattern).matcher(text);
int pos = 0;
while (matcher.find(pos) && !matcher.group().isEmpty()) {
int start = matcher.start();
int end = matcher.end();
highlighter.addHighlight(start, end, painter);
pos = end;
}
} catch (BadLocationException | PatternSyntaxException ex) {
UIManager.getLookAndFeel().provideErrorFeedback(jtc);
}
jtc.repaint();
}
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));
}
@Override
protected void formatTextComponent(String text, StyledDocument doc,
int selectionStart, int selectionEnd) throws BadLocationException {
Token[] tokens = getTokens(text, true);
final Map<Token, AttributeSet> tokenAttributes = new TreeMap<Token, AttributeSet>();
for (int index = 0; index < tokens.length; index++) {
HighlightPainter painter = getHighlightPainter(tokens, index,
selectionStart, selectionEnd);
if (painter != null) {
allHighlights.add(jtc.getHighlighter().addHighlight(
tokens[index].getDocumentStartIndex(),
tokens[index].getDocumentEndIndex(), painter));
}
AttributeSet attributes = getAttributes(tokens, index,
selectionStart, selectionEnd);
if (attributes != null) {
tokenAttributes.put(tokens[index], attributes);
}
}
for (Token token : tokenAttributes.keySet()) {
AttributeSet attr = tokenAttributes.get(token);
doc.setCharacterAttributes(token.getDocumentStartIndex(),
token.getLength(), attr, true);
}
}
private void highlightText(JTextArea area, int start, int end) {
Highlighter hilite = area.getHighlighter();
HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
try {
hilite.addHighlight(start, end, painter);
} catch (BadLocationException e) {
logger.error(e.getMessage(), e);
}
}
@Override protected Highlighter.HighlightPainter getSelectionPainter() {
// JComponent c = getComponent();
// boolean selected = c.hasFocus();
// Container f = SwingUtilities.getAncestorOfClass(JInternalFrame.class, c);
// if (f instanceof JInternalFrame) {
// System.out.println("bbbbbbbbbbbbbb");
// JInternalFrame frame = (JInternalFrame) f;
// selected = frame.isSelected();
// }
// return selected ? DefaultHighlighter.DefaultPainter : nonFocusHighlightPainter;
return getComponent().hasFocus() ? DefaultHighlighter.DefaultPainter : NONFOCUS;
}
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));
}
/** @return the HighlightPainter for tokenIndex in the list of tokens. */
protected HighlightPainter getHighlightPainter(Token[] allToken,
int tokenIndex, int selectionStart, int selectionEnd) {
return null;
}
protected FocusCaret(HighlightPainter selectionPainter, HighlightPainter nonFocusPainter) {
super();
this.selectionPainter = selectionPainter;
this.nonFocusPainter = nonFocusPainter;
}
@Override protected HighlightPainter getSelectionPainter() {
return getComponent().hasFocus() ? selectionPainter : nonFocusPainter;
}
@Override
public HighlightPainter linkPainter() {
return underLinePainter;
}