小编smi*_*8ar的帖子

更改 jTextPane 中选定文本的颜色

我正在使用 JTextPane 创建一个文本编辑器,它允许用户更改所选文本的颜色。但是,当用户选择文本,然后选择更改颜色的选项(例如,更改为红色)时,文本不会显示为红色,直到取消选择文本。我尝试使用 setSelectedTextColor 来更改所选文本的颜色,但这不起作用,因为此后无论何时选择文本都会将文本更改为红色。有没有办法让选定的文本显示为它的实际颜色?Or like the way it works in Word where it's not the actual color of the text, but when text of different colors are selected they show up as different colors even when selected.

我使用以下代码设置 JTextPane 和将所选文本更改为红色的按钮:

JButton redButton = new JButton(new StyledEditorKit.ForegroundAction("red", Color.RED));
redButton.setFocusable(false);
buttonPanel.add(redButton);
Run Code Online (Sandbox Code Playgroud)

JTextPane 设置为内容类型 HTML 并使用 HTMLEditorKit:

p=new JTextPane();
p.setSize(300, 300);
kit = new HTMLEditorKit();
p.setEditorKit(kit);
p.setDocument(kit.createDefaultDocument());

p.setContentType("text/html");
p.setEditable(true);
Run Code Online (Sandbox Code Playgroud)

如果您需要更多源代码来理解这个问题,请告诉我。谢谢你!

java swing colors jtextpane swing-highlighter

6
推荐指数
2
解决办法
3104
查看次数

标签 统计

colors ×1

java ×1

jtextpane ×1

swing ×1

swing-highlighter ×1