может быть (Стас и Роб) реализован собственный Маркером, где требуется, чтобы overrive Прямоугольник/Форма от API против Mouse_selection
но более комфортабельный будет использовать JTextPane с AttributeSet, но пропустить там Highlighter с цветным прямоугольником
, например
import java.awt.Color;
import javax.swing.*;
import javax.swing.text.*;
public class ColorPane extends JTextPane {
private static final long serialVersionUID = 1L;
public void appendNaive(Color c, String s) { // naive implementation
// bad: instiantiates a new AttributeSet object on each call
SimpleAttributeSet aset = new SimpleAttributeSet();
StyleConstants.setForeground(aset, c);
int len = getText().length();
setCaretPosition(len); // place caret at the end (with no selection)
setCharacterAttributes(aset, false);
replaceSelection(s); // there is no selection, so inserts at caret
}
public void append(Color c, String s) { // better implementation--uses
StyleContext sc = StyleContext.getDefaultStyleContext(); // StyleContext
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY,
StyleConstants.Foreground, c);
int len = getDocument().getLength(); // same value as
//getText().length();
setCaretPosition(len); // place caret at the end (with no selection)
setCharacterAttributes(aset, false);
replaceSelection(s); // there is no selection, so inserts at caret
}
public static void main(String argv[]) {
UIManager.put("TextPane.selectionBackground", Color.yellow);
UIManager.put("TextPane.selectionForeground", Color.blue);
ColorPane pane = new ColorPane();
for (int n = 1; n <= 400; n += 1) {
if (isPrime(n)) {
pane.append(Color.red, String.valueOf(n) + ' ');
} else if (isPerfectSquare(n)) {
pane.append(Color.blue, String.valueOf(n) + ' ');
} else {
pane.append(Color.black, String.valueOf(n) + ' ');
}
}
JFrame f = new JFrame("ColorPane example");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(new JScrollPane(pane));
f.setSize(600, 400);
f.setVisible(true);
}
public static boolean isPrime(int n) {
if (n < 2) {
return false;
}
double max = Math.sqrt(n);
for (int j = 2; j <= max; j += 1) {
if (n % j == 0) {
return false; // j is a factor
}
}
return true;
}
public static boolean isPerfectSquare(int n) {
int j = 1;
while (j * j < n && j * j > 0) {
j += 1;
}
return (j * j == n);
}
}
или преобразовать этот код из CARET в Painter
class HighlightCaret extends DefaultCaret {
private static final Highlighter.HighlightPainter unfocusedPainter = new DefaultHighlighter.DefaultHighlightPainter(new Color(230, 230, 210));
private static final long serialVersionUID = 1L;
private boolean isFocused;
@Override
protected Highlighter.HighlightPainter getSelectionPainter() {
return isFocused ? super.getSelectionPainter() : unfocusedPainter;
}
@Override
public void setSelectionVisible(boolean hasFocus) {
if (hasFocus != isFocused) {
isFocused = hasFocus;
super.setSelectionVisible(false);
super.setSelectionVisible(true);
}
}
}
Вы имеете в виду вы не хотите, чтобы применить фломастер к выбранному тексту? – Thomas
Я все еще хочу применить маркер всякий раз, когда вы используете мышь. Я хочу сохранить выделение, которое я установил, но когда я использую мышь, чтобы выделить этот выделенный текст, я хочу, чтобы подсветка мыши вступила в силу (т. Е. Текст подчеркивает изменения синего цвета). Когда мышь больше не выделяет этот текст, он возвращается к моей подсветке, которую я установил на нем. – Decrypter
Можете ли вы подробнее рассказать о нем? Как вы используете мышь, чтобы выделить текст - наведите указатель мыши на какой-либо текст или выделенный текст? Не могли бы вы предоставить небольшой скриншот, который показывает, чего вы хотите достичь? – Thomas