我需要知道如何做到这一点:
让我们说:我有一个JTextArea像这样的代码:
LOAD R1, 1
DEC R1
STORE M, R1
ADD R4, R1,8
Run Code Online (Sandbox Code Playgroud)
我想改变的颜色LOAD,DEC,STORE并ADD以颜色为蓝色
R1,R4以色绿
M到红号橙色
如何更改此文字的颜色?这些文本来自记事本或可以直接键入文本区域.
问题1:通过使用defaulthighlighter,我可以使聚焦线变为蓝色.现在我想把它换成其他颜色.有谁知道如何更改此参数? - - 解决了
问题2:pos是我想要突出显示的子串的起始索引.我用setCaretPosition(pos); 更新显示内容.但它总是出现在窗口的底部.我希望它在顶部.谁能告诉我如何处理?
我使用一个演示来显示我的问题:
import java.awt.Color;
import java.net.MalformedURLException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
public class Test {
public static void main(final String[] args) throws MalformedURLException {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
init();
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
private static void init() throws BadLocationException {
JFrame frame = new JFrame();
final JTextArea textArea …Run Code Online (Sandbox Code Playgroud) 我想为文本区域中的特定行设置颜色.到目前为止我发现的是以下内容
// Declarations
private final DefaultStyledDocument document;
private final MutableAttributeSet homeAttributeSet;
private final MutableAttributeSet awayAttributeSet;
// Usage in the form constructor
jTextAreaLog.setDocument(document);
homeAttributeSet = new SimpleAttributeSet();
StyleConstants.setForeground(homeAttributeSet, Color.blue);
StyleConstants.setItalic(homeAttributeSet, true);
awayAttributeSet = new SimpleAttributeSet();
StyleConstants.setForeground(awayAttributeSet, Color.red);
// Setting the style of the last line
final int start = jTextAreaLog.getLineStartOffset(jTextAreaLog.getLineCount() - 2);
final int length = jTextAreaLog.getLineEndOffset(jTextAreaLog.getLineCount() - 1) - start;
document.setCharacterAttributes(start, length, awayAttributeSet, true);
Run Code Online (Sandbox Code Playgroud)
但这不起作用.我究竟做错了什么?
编辑:好的,我一直在尝试,我尝试使用
final int end = jTextAreaLog.getLineEndOffset(jTextAreaLog.getLineCount() - 1);
document.insertString(end, "someText", awayAttributeSet);
Run Code Online (Sandbox Code Playgroud)
添加文本而不是添加然后重新打印,但无济于事.