我一直在寻找这个,到目前为止,我能够想出的是如何创建一个样式并将其应用于这样的角色:
StyledDocument doc = (StyledDocument) new DefaultStyledDocument();
JTextPane textpane = new JTextPane(doc);
textpane.setText("Test");
javax.swing.text.Style style = textpane.addStyle("Red", null);
StyleConstants.setForeground(style, Color.RED);
doc.setCharacterAttributes(0, 1, textpane.getStyle("Red"), true);
Run Code Online (Sandbox Code Playgroud)
如果您的文档中只有少量样式并希望按名称存储它们,以便以后可以轻松应用它们,这将非常有用.在我的应用程序中,我希望能够为文本中的每个字符独立设置前景色(仅少数值之一)和背景色(灰度,许多不同的值).为此创建潜在的数百/数千种不同风格似乎是一种巨大的浪费.有没有办法设置这些属性,而不必每次都创建一个新的样式?如果我只需渲染文本会更容易,但我也需要使其可编辑.有没有办法做到这一点JTextPane,还是有另一个提供此功能的swing类?
我在一个框架中打开一个文件,我想强调一些单词.据我所知,我需要遍历文件的内容.如何遍历内容以及我可能用于突出显示的相关属性是什么?
更新:我的代码似乎有点像这样
private JEditorPane editorpane;
JScrollPane editorScrollPane;
public TextEditor()
{
editorpane = new JEditorPane();
editorpane.setEditable(false);
if (filename != null)
{
try
{
File file = new File(filename);
editorpane.setPage(file.toURI().toURL());
}
catch (IOException e)
{
e.printStackTrace();
System.err.println("Attempted to read a bad file ...");
}
}
else
{
System.err.println("File name is wrong");
}
add(editorpane);
}
Run Code Online (Sandbox Code Playgroud) 如果你有人回答,请告诉我.基本上需要像谷歌搜索引擎,当我们按任意键然后它将显示建议相关的按键.
关于Satish Dhiman