Java 如何为jTextArea中选定的文本设置字体颜色?
我必须为jTextArea中选定的文本设置定义的颜色(如红色)。这就像文本区域中的高亮显示过程(jTextArea)。当我选择特定的文本并单击任何按钮时,它应该以预定义的颜色进行更改Java 如何为jTextArea中选定的文本设置字体颜色?,java,jtextarea,Java,Jtextarea,我必须为jTextArea中选定的文本设置定义的颜色(如红色)。这就像文本区域中的高亮显示过程(jTextArea)。当我选择特定的文本并单击任何按钮时,它应该以预定义的颜色进行更改 如果有任何解决方案,我可以将jTextArea更改为jTextPane或JEditorPane 首先,您不能使用JTextArea执行此操作,因为它是纯文本区域。您必须使用像JEditorPane这样的样式化文本区域。请参阅。您可以使用HTMLDocument并执行所需操作。请参阅首先,您不能使用JTextArea
如果有任何解决方案,我可以将jTextArea更改为jTextPane或JEditorPane 首先,您不能使用JTextArea执行此操作,因为它是纯文本区域。您必须使用像JEditorPane这样的样式化文本区域。请参阅。您可以使用HTMLDocument并执行所需操作。请参阅首先,您不能使用JTextArea执行此操作,因为它是纯文本区域。您必须使用像JEditorPane这样的样式化文本区域。请参阅。您可以使用HTMLDocument并执行您想要的操作。请参见样式文本(带有字符的颜色属性)作为样式文档提供,并可在JTextPane和JEditorPane中使用。因此,请使用JTextPane
private void buttonActionPerformed(java.awt.event.ActionEvent evt) {
StyledDocument doc = textPane.getStyledDocument();
int start = textPane.getSelectionStart();
int end = textPane.getSelectionEnd();
if (start == end) { // No selection, cursor position.
return;
}
if (start > end) { // Backwards selection?
int life = start;
start = end;
end = life;
}
Style style = textPane.addStyle("MyHilite", null);
StyleConstants.setForeground(style, Color.GREEN.darker());
//style = textPane.getStyle("MyHilite");
doc.setCharacterAttributes(start, end - start, style, false);
}
注意:可以在创建JTextPane时设置样式,如注释外的代码所示,从JTextPane字段中检索样式文本。样式文本(带有字符的颜色属性)可作为样式文档使用,并可在JTextPane和JEditorPane中使用。因此,请使用JTextPane
private void buttonActionPerformed(java.awt.event.ActionEvent evt) {
StyledDocument doc = textPane.getStyledDocument();
int start = textPane.getSelectionStart();
int end = textPane.getSelectionEnd();
if (start == end) { // No selection, cursor position.
return;
}
if (start > end) { // Backwards selection?
int life = start;
start = end;
end = life;
}
Style style = textPane.addStyle("MyHilite", null);
StyleConstants.setForeground(style, Color.GREEN.darker());
//style = textPane.getStyle("MyHilite");
doc.setCharacterAttributes(start, end - start, style, false);
}
注意:可以在创建JTextPane时设置样式,正如注释过的代码所示,从JTextPane字段中检索。显示您迄今为止尝试过的代码。
JTextPane
或JEditorPane
可能是您在此处的更好选择。感谢berry,如果有任何解决方案,我可以将其更改为JTextPane或JEditorPane。您的答案,以及工作示例:EnKrypt,我尝试了jTextArea1。setSelectedTextColor(Color.red); 但当我选择特定文本时,颜色会发生变化。我想将其设置为固定,直到我关闭窗口为止,就像荧光笔一样。向我们展示您迄今为止尝试过的代码。JTextPane
或JEditorPane
可能是您在这里的更好选择。感谢berry,如果有任何解决方案,我可以将其更改为JTextPane或JEditorPane。您的答案,以及工作示例:EnKrypt,我尝试使用jTextArea1.setSelectedTextColor(Color.red);但当我选择特定文本时,颜色会发生变化。我想把它设置为固定的,直到我关闭窗口,就像荧光灯一样。谢谢你们,我认为这个代码可以工作。如何在其中使用StyledDocument和其他样式?它显示“找不到符号”。必须有一个JTextPane textPane和import javax.swing.text.*
。还有一个JButton和addActionListener之类的东西。谢谢你,我认为这段代码很有效。如何在其中使用StyledDocument和其他样式?它显示“找不到符号”。必须有一个JTextPane textPane和import javax.swing.text.*
。然后有一个JButton和addActionListener之类的东西。