下面列出了怎么用javax.swing.text.Highlighter的API类实例代码及写法,或者点击链接到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;
}
/**
* add highlights for the given region on the given pane
* @param pane
* @param start
* @param end
* @param marker
*/
public static void markText(JTextComponent pane, int start, int end, SimpleMarker marker) {
try {
Highlighter hiliter = pane.getHighlighter();
int selStart = pane.getSelectionStart();
int selEnd = pane.getSelectionEnd();
// if there is no selection or selection does not overlap
if(selStart == selEnd || end < selStart || start > selStart) {
hiliter.addHighlight(start, end, marker);
return;
}
// selection starts within the highlight, highlight before slection
if(selStart > start && selStart < end ) {
hiliter.addHighlight(start, selStart, marker);
}
// selection ends within the highlight, highlight remaining
if(selEnd > start && selEnd < end ) {
hiliter.addHighlight(selEnd, end, marker);
}
} catch (BadLocationException ex) {
// nothing we can do if the request is out of bound
LOG.log(Level.SEVERE, null, ex);
}
}
/** Add a highlighted region based on the positions in an Info object. */
private void addHighlight(Highlighter h, Info info, Color c) {
int start = info.start;
int end = info.end;
if (start == -1 && end == -1)
return;
if (start == -1)
start = end;
if (end == -1)
end = start;
try {
h.addHighlight(info.start, info.end,
new DefaultHighlighter.DefaultHighlightPainter(c));
if (info.pos != -1) {
Color c2 = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int)(.4f * 255)); // 40%
h.addHighlight(info.pos, info.pos + 1,
new DefaultHighlighter.DefaultHighlightPainter(c2));
}
} catch (BadLocationException e) {
e.printStackTrace();
}
}
/** Add a highlighted region based on the positions in an Info object. */
private void addHighlight(Highlighter h, Info info, Color c) {
int start = info.start;
int end = info.end;
if (start == -1 && end == -1)
return;
if (start == -1)
start = end;
if (end == -1)
end = start;
try {
h.addHighlight(info.start, info.end,
new DefaultHighlighter.DefaultHighlightPainter(c));
if (info.pos != -1) {
Color c2 = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int)(.4f * 255)); // 40%
h.addHighlight(info.pos, info.pos + 1,
new DefaultHighlighter.DefaultHighlightPainter(c2));
}
} catch (BadLocationException e) {
e.printStackTrace();
}
}
/**
* Determines whether the SelectedTextColor should be used for painting text
* foreground for the specified highlight.
*
* Returns true only if the highlight painter for the specified highlight
* is the swing painter (whether inner class of javax.swing.text.DefaultHighlighter
* or com.sun.java.swing.plaf.windows.WindowsTextUI) and its background color
* is null or equals to the selection color of the text component.
*
* This is a hack for fixing both bugs 4761990 and 5003294
*/
public static boolean useSelectedTextColor(Highlighter.Highlight h, JTextComponent c) {
Highlighter.HighlightPainter painter = h.getPainter();
String painterClass = painter.getClass().getName();
if (painterClass.indexOf("javax.swing.text.DefaultHighlighter") != 0 &&
painterClass.indexOf("com.sun.java.swing.plaf.windows.WindowsTextUI") != 0) {
return false;
}
try {
DefaultHighlighter.DefaultHighlightPainter defPainter =
(DefaultHighlighter.DefaultHighlightPainter) painter;
if (defPainter.getColor() != null &&
!defPainter.getColor().equals(c.getSelectionColor())) {
return false;
}
} catch (ClassCastException e) {
return false;
}
return true;
}
/**
* add highlights for the given region on the given pane
*
* @param pane Editor
* @param start Start index
* @param end End index
* @param marker Marker
*/
public static void markText(JTextComponent pane, int start, int end, Highlighter.HighlightPainter marker) {
try {
Highlighter hiliter = pane.getHighlighter();
int selStart = pane.getSelectionStart();
int selEnd = pane.getSelectionEnd();
// if there is no selection or selection does not overlap
if (selStart == selEnd || end < selStart || start > selStart) {
hiliter.addHighlight(start, end, marker);
return;
}
// selection starts within the highlight, highlight before slection
if (selStart > start && selStart < end) {
hiliter.addHighlight(start, selStart, marker);
}
// selection ends within the highlight, highlight remaining
if (selEnd > start && selEnd < end) {
hiliter.addHighlight(selEnd, end, marker);
}
} catch (BadLocationException ex) {
}
}
/** Show an entry that has been selected. */
private void showEntry(Entry e) {
try {
// update simple fields
setTitle(e.file.getName());
checkField.setText(e.check);
enclPanel.setInfo(e.encl);
selfPanel.setInfo(e.self);
// show file text with highlights
body.setText(e.file.getCharContent(true).toString());
Highlighter highlighter = body.getHighlighter();
highlighter.removeAllHighlights();
addHighlight(highlighter, e.encl, enclColor);
addHighlight(highlighter, e.self, selfColor);
scroll(body, getMinPos(enclPanel.info, selfPanel.info));
} catch (IOException ex) {
body.setText("Cannot read " + e.file.getName() + ": " + e);
}
}
/** Add a highlighted region based on the positions in an Info object. */
private void addHighlight(Highlighter h, Info info, Color c) {
int start = info.start;
int end = info.end;
if (start == -1 && end == -1)
return;
if (start == -1)
start = end;
if (end == -1)
end = start;
try {
h.addHighlight(info.start, info.end,
new DefaultHighlighter.DefaultHighlightPainter(c));
if (info.pos != -1) {
Color c2 = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int)(.4f * 255)); // 40%
h.addHighlight(info.pos, info.pos + 1,
new DefaultHighlighter.DefaultHighlightPainter(c2));
}
} catch (BadLocationException e) {
e.printStackTrace();
}
}
/** Show an entry that has been selected. */
private void showEntry(Entry e) {
try {
// update simple fields
setTitle(e.file.getName());
checkField.setText(e.check);
enclPanel.setInfo(e.encl);
selfPanel.setInfo(e.self);
// show file text with highlights
body.setText(e.file.getCharContent(true).toString());
Highlighter highlighter = body.getHighlighter();
highlighter.removeAllHighlights();
addHighlight(highlighter, e.encl, enclColor);
addHighlight(highlighter, e.self, selfColor);
scroll(body, getMinPos(enclPanel.info, selfPanel.info));
} catch (IOException ex) {
body.setText("Cannot read " + e.file.getName() + ": " + e);
}
}
protected void highlight(JTextComponent comp, int i, int j, boolean scroll) {
Highlighter highlighter = comp.getHighlighter();
highlighter.removeAllHighlights();
try {
i = toComponentPosition(comp, i);
j = toComponentPosition(comp, j);
highlighter.addHighlight(i, j+1, DefaultHighlighter.DefaultPainter);
if ( scroll ) {
if ( comp.getCaretPosition()< i || comp.getCaretPosition()>j ) {
comp.moveCaretPosition(i);
comp.scrollRectToVisible(comp.modelToView(i));
}
}
}
catch (BadLocationException ble) {
errMgr.internalError(tmodel.root.event.scope.st, "bad highlight location", ble);
}
}
/** Show an entry that has been selected. */
private void showEntry(Entry e) {
try {
// update simple fields
setTitle(e.file.getName());
checkField.setText(e.check);
enclPanel.setInfo(e.encl);
selfPanel.setInfo(e.self);
// show file text with highlights
body.setText(e.file.getCharContent(true).toString());
Highlighter highlighter = body.getHighlighter();
highlighter.removeAllHighlights();
addHighlight(highlighter, e.encl, enclColor);
addHighlight(highlighter, e.self, selfColor);
scroll(body, getMinPos(enclPanel.info, selfPanel.info));
} catch (IOException ex) {
body.setText("Cannot read " + e.file.getName() + ": " + e);
}
}
/** Add a highlighted region based on the positions in an Info object. */
private void addHighlight(Highlighter h, Info info, Color c) {
int start = info.start;
int end = info.end;
if (start == -1 && end == -1)
return;
if (start == -1)
start = end;
if (end == -1)
end = start;
try {
h.addHighlight(info.start, info.end,
new DefaultHighlighter.DefaultHighlightPainter(c));
if (info.pos != -1) {
Color c2 = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int)(.4f * 255)); // 40%
h.addHighlight(info.pos, info.pos + 1,
new DefaultHighlighter.DefaultHighlightPainter(c2));
}
} catch (BadLocationException e) {
e.printStackTrace();
}
}
/**
* Determines whether the SelectedTextColor should be used for painting text
* foreground for the specified highlight.
*
* Returns true only if the highlight painter for the specified highlight
* is the swing painter (whether inner class of javax.swing.text.DefaultHighlighter
* or com.sun.java.swing.plaf.windows.WindowsTextUI) and its background color
* is null or equals to the selection color of the text component.
*
* This is a hack for fixing both bugs 4761990 and 5003294
*/
public static boolean useSelectedTextColor(Highlighter.Highlight h, JTextComponent c) {
Highlighter.HighlightPainter painter = h.getPainter();
String painterClass = painter.getClass().getName();
if (painterClass.indexOf("javax.swing.text.DefaultHighlighter") != 0 &&
painterClass.indexOf("com.sun.java.swing.plaf.windows.WindowsTextUI") != 0) {
return false;
}
try {
DefaultHighlighter.DefaultHighlightPainter defPainter =
(DefaultHighlighter.DefaultHighlightPainter) painter;
if (defPainter.getColor() != null &&
!defPainter.getColor().equals(c.getSelectionColor())) {
return false;
}
} catch (ClassCastException e) {
return false;
}
return true;
}
/** Show an entry that has been selected. */
private void showEntry(Entry e) {
try {
// update simple fields
setTitle(e.file.getName());
checkField.setText(e.check);
enclPanel.setInfo(e.encl);
selfPanel.setInfo(e.self);
// show file text with highlights
body.setText(e.file.getCharContent(true).toString());
Highlighter highlighter = body.getHighlighter();
highlighter.removeAllHighlights();
addHighlight(highlighter, e.encl, enclColor);
addHighlight(highlighter, e.self, selfColor);
scroll(body, getMinPos(enclPanel.info, selfPanel.info));
} catch (IOException ex) {
body.setText("Cannot read " + e.file.getName() + ": " + e);
}
}
/**
* Determines whether the SelectedTextColor should be used for painting text
* foreground for the specified highlight.
*
* Returns true only if the highlight painter for the specified highlight
* is the swing painter (whether inner class of javax.swing.text.DefaultHighlighter
* or com.sun.java.swing.plaf.windows.WindowsTextUI) and its background color
* is null or equals to the selection color of the text component.
*
* This is a hack for fixing both bugs 4761990 and 5003294
*/
public static boolean useSelectedTextColor(Highlighter.Highlight h, JTextComponent c) {
Highlighter.HighlightPainter painter = h.getPainter();
String painterClass = painter.getClass().getName();
if (painterClass.indexOf("javax.swing.text.DefaultHighlighter") != 0 &&
painterClass.indexOf("com.sun.java.swing.plaf.windows.WindowsTextUI") != 0) {
return false;
}
try {
DefaultHighlighter.DefaultHighlightPainter defPainter =
(DefaultHighlighter.DefaultHighlightPainter) painter;
if (defPainter.getColor() != null &&
!defPainter.getColor().equals(c.getSelectionColor())) {
return false;
}
} catch (ClassCastException e) {
return false;
}
return true;
}
private void update() {
if (regexModel.getRegex() == null || regexModel.getTestValue() == null) {
return;
}
RegexTestInput input = new RegexTestInput(regexModel.getRegex(), regexModel.getTestValue());
RegexTestResult result = RegexTester.test(input);
matchField.setText(String.format(MATCHES_LABEL, result.isMatch()));
lookingAtField.setText(String.format(LOOKING_AT_LABEL, result.isLookingAt()));
resultField.setText(result.getResult());
captureField.setText(result.getCapture());
captureField.setCaretPosition(0);
Highlighter highlighter = resultField.getHighlighter();
for (RegexTestResult.Group group : result.getGroups()) {
try {
highlighter.addHighlight(group.getStart(), group.getEnd(), highlightPainter);
} catch (BadLocationException ignore) {
}
}
}
public static void setHighlight(JTextComponent jtc, String pattern) {
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, HIGHLIGHT);
pos = end;
}
} catch (BadLocationException | PatternSyntaxException ex) {
UIManager.getLookAndFeel().provideErrorFeedback(jtc);
}
}
@Override protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) {
super.paintTrack(g, c, trackBounds);
Rectangle rect = textArea.getBounds();
double sy = trackBounds.getHeight() / rect.getHeight();
AffineTransform at = AffineTransform.getScaleInstance(1d, sy);
Highlighter highlighter = textArea.getHighlighter();
g.setColor(Color.YELLOW);
try {
for (Highlighter.Highlight hh: highlighter.getHighlights()) {
Rectangle r = textArea.modelToView(hh.getStartOffset());
Rectangle s = at.createTransformedShape(r).getBounds();
int h = 2; // Math.max(2, s.height - 2);
g.fillRect(trackBounds.x, trackBounds.y + s.y, trackBounds.width, h);
}
} catch (BadLocationException ex) {
// should never happen
RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
wrap.initCause(ex);
throw wrap;
}
}
/**
* Determines whether the SelectedTextColor should be used for painting text
* foreground for the specified highlight.
*
* Returns true only if the highlight painter for the specified highlight
* is the swing painter (whether inner class of javax.swing.text.DefaultHighlighter
* or com.sun.java.swing.plaf.windows.WindowsTextUI) and its background color
* is null or equals to the selection color of the text component.
*
* This is a hack for fixing both bugs 4761990 and 5003294
*/
public static boolean useSelectedTextColor(Highlighter.Highlight h, JTextComponent c) {
Highlighter.HighlightPainter painter = h.getPainter();
String painterClass = painter.getClass().getName();
if (painterClass.indexOf("javax.swing.text.DefaultHighlighter") != 0 &&
painterClass.indexOf("com.sun.java.swing.plaf.windows.WindowsTextUI") != 0) {
return false;
}
try {
DefaultHighlighter.DefaultHighlightPainter defPainter =
(DefaultHighlighter.DefaultHighlightPainter) painter;
if (defPainter.getColor() != null &&
!defPainter.getColor().equals(c.getSelectionColor())) {
return false;
}
} catch (ClassCastException e) {
return false;
}
return true;
}
/** Show an entry that has been selected. */
private void showEntry(Entry e) {
try {
// update simple fields
setTitle(e.file.getName());
checkField.setText(e.check);
enclPanel.setInfo(e.encl);
selfPanel.setInfo(e.self);
// show file text with highlights
body.setText(e.file.getCharContent(true).toString());
Highlighter highlighter = body.getHighlighter();
highlighter.removeAllHighlights();
addHighlight(highlighter, e.encl, enclColor);
addHighlight(highlighter, e.self, selfColor);
scroll(body, getMinPos(enclPanel.info, selfPanel.info));
} catch (IOException ex) {
body.setText("Cannot read " + e.file.getName() + ": " + e);
}
}
/** Add a highlighted region based on the positions in an Info object. */
private void addHighlight(Highlighter h, Info info, Color c) {
int start = info.start;
int end = info.end;
if (start == -1 && end == -1)
return;
if (start == -1)
start = end;
if (end == -1)
end = start;
try {
h.addHighlight(info.start, info.end,
new DefaultHighlighter.DefaultHighlightPainter(c));
if (info.pos != -1) {
Color c2 = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int)(.4f * 255)); // 40%
h.addHighlight(info.pos, info.pos + 1,
new DefaultHighlighter.DefaultHighlightPainter(c2));
}
} catch (BadLocationException e) {
e.printStackTrace();
}
}
/** Show an entry that has been selected. */
private void showEntry(Entry e) {
try {
// update simple fields
setTitle(e.file.getName());
checkField.setText(e.check);
enclPanel.setInfo(e.encl);
selfPanel.setInfo(e.self);
// show file text with highlights
body.setText(e.file.getCharContent(true).toString());
Highlighter highlighter = body.getHighlighter();
highlighter.removeAllHighlights();
addHighlight(highlighter, e.encl, enclColor);
addHighlight(highlighter, e.self, selfColor);
scroll(body, getMinPos(enclPanel.info, selfPanel.info));
} catch (IOException ex) {
body.setText("Cannot read " + e.file.getName() + ": " + e);
}
}
/**
* Determines whether the SelectedTextColor should be used for painting text
* foreground for the specified highlight.
*
* Returns true only if the highlight painter for the specified highlight
* is the swing painter (whether inner class of javax.swing.text.DefaultHighlighter
* or com.sun.java.swing.plaf.windows.WindowsTextUI) and its background color
* is null or equals to the selection color of the text component.
*
* This is a hack for fixing both bugs 4761990 and 5003294
*/
public static boolean useSelectedTextColor(Highlighter.Highlight h, JTextComponent c) {
Highlighter.HighlightPainter painter = h.getPainter();
String painterClass = painter.getClass().getName();
if (painterClass.indexOf("javax.swing.text.DefaultHighlighter") != 0 &&
painterClass.indexOf("com.sun.java.swing.plaf.windows.WindowsTextUI") != 0) {
return false;
}
try {
DefaultHighlighter.DefaultHighlightPainter defPainter =
(DefaultHighlighter.DefaultHighlightPainter) painter;
if (defPainter.getColor() != null &&
!defPainter.getColor().equals(c.getSelectionColor())) {
return false;
}
} catch (ClassCastException e) {
return false;
}
return true;
}
/** Show an entry that has been selected. */
private void showEntry(Entry e) {
try {
// update simple fields
setTitle(e.file.getName());
checkField.setText(e.check);
enclPanel.setInfo(e.encl);
selfPanel.setInfo(e.self);
// show file text with highlights
body.setText(e.file.getCharContent(true).toString());
Highlighter highlighter = body.getHighlighter();
highlighter.removeAllHighlights();
addHighlight(highlighter, e.encl, enclColor);
addHighlight(highlighter, e.self, selfColor);
scroll(body, getMinPos(enclPanel.info, selfPanel.info));
} catch (IOException ex) {
body.setText("Cannot read " + e.file.getName() + ": " + e);
}
}
/** Add a highlighted region based on the positions in an Info object. */
private void addHighlight(Highlighter h, Info info, Color c) {
int start = info.start;
int end = info.end;
if (start == -1 && end == -1)
return;
if (start == -1)
start = end;
if (end == -1)
end = start;
try {
h.addHighlight(info.start, info.end,
new DefaultHighlighter.DefaultHighlightPainter(c));
if (info.pos != -1) {
Color c2 = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int)(.4f * 255)); // 40%
h.addHighlight(info.pos, info.pos + 1,
new DefaultHighlighter.DefaultHighlightPainter(c2));
}
} catch (BadLocationException e) {
e.printStackTrace();
}
}
/** Show an entry that has been selected. */
private void showEntry(Entry e) {
try {
// update simple fields
setTitle(e.file.getName());
checkField.setText(e.check);
enclPanel.setInfo(e.encl);
selfPanel.setInfo(e.self);
// show file text with highlights
body.setText(e.file.getCharContent(true).toString());
Highlighter highlighter = body.getHighlighter();
highlighter.removeAllHighlights();
addHighlight(highlighter, e.encl, enclColor);
addHighlight(highlighter, e.self, selfColor);
scroll(body, getMinPos(enclPanel.info, selfPanel.info));
} catch (IOException ex) {
body.setText("Cannot read " + e.file.getName() + ": " + e);
}
}
/** Add a highlighted region based on the positions in an Info object. */
private void addHighlight(Highlighter h, Info info, Color c) {
int start = info.start;
int end = info.end;
if (start == -1 && end == -1)
return;
if (start == -1)
start = end;
if (end == -1)
end = start;
try {
h.addHighlight(info.start, info.end,
new DefaultHighlighter.DefaultHighlightPainter(c));
if (info.pos != -1) {
Color c2 = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int)(.4f * 255)); // 40%
h.addHighlight(info.pos, info.pos + 1,
new DefaultHighlighter.DefaultHighlightPainter(c2));
}
} catch (BadLocationException e) {
e.printStackTrace();
}
}
/**
* Determines whether the SelectedTextColor should be used for painting text
* foreground for the specified highlight.
*
* Returns true only if the highlight painter for the specified highlight
* is the swing painter (whether inner class of javax.swing.text.DefaultHighlighter
* or com.sun.java.swing.plaf.windows.WindowsTextUI) and its background color
* is null or equals to the selection color of the text component.
*
* This is a hack for fixing both bugs 4761990 and 5003294
*/
public static boolean useSelectedTextColor(Highlighter.Highlight h, JTextComponent c) {
Highlighter.HighlightPainter painter = h.getPainter();
String painterClass = painter.getClass().getName();
if (painterClass.indexOf("javax.swing.text.DefaultHighlighter") != 0 &&
painterClass.indexOf("com.sun.java.swing.plaf.windows.WindowsTextUI") != 0) {
return false;
}
try {
DefaultHighlighter.DefaultHighlightPainter defPainter =
(DefaultHighlighter.DefaultHighlightPainter) painter;
if (defPainter.getColor() != null &&
!defPainter.getColor().equals(c.getSelectionColor())) {
return false;
}
} catch (ClassCastException e) {
return false;
}
return true;
}
/** Show an entry that has been selected. */
private void showEntry(Entry e) {
try {
// update simple fields
setTitle(e.file.getName());
checkField.setText(e.check);
enclPanel.setInfo(e.encl);
selfPanel.setInfo(e.self);
// show file text with highlights
body.setText(e.file.getCharContent(true).toString());
Highlighter highlighter = body.getHighlighter();
highlighter.removeAllHighlights();
addHighlight(highlighter, e.encl, enclColor);
addHighlight(highlighter, e.self, selfColor);
scroll(body, getMinPos(enclPanel.info, selfPanel.info));
} catch (IOException ex) {
body.setText("Cannot read " + e.file.getName() + ": " + e);
}
}