【发布时间】:2012-10-28 10:36:30
【问题描述】:
我正在尝试使用JTextPane 制作一个小的 HTML-wysiwyg,但我无法让 BackgroundAction 工作。我在JTextPane 的StyledDocument 上使用setCharacterAttributes,但这似乎有问题。视图还可以,但Document 不行。
这是一个显示问题的小演示代码。有2个JTextPane:
- 我在第一个中设置了文本的背景颜色
- 我检索第一个
JTextPane的文本并将其设置在第二个上
--> 尽管文本相同,但它们显示的内容不同。
有没有办法在当前选定的文本上设置背景颜色并让JTextPane 报告更新的 HTML 文本?
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class TestDifferentStyles {
private void initUI() {
JFrame frame = new JFrame(TestDifferentStyles.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextPane textPane = new JTextPane();
final JTextPane textPane2 = new JTextPane();
textPane2.setEditable(false);
textPane.setContentType("text/html");
textPane2.setContentType("text/html");
textPane.setText("<html><head></head><body><p>Hello world</p></body></html>");
SimpleAttributeSet set = new SimpleAttributeSet();
StyleConstants.setForeground(set, Color.GREEN);
StyleConstants.setBackground(set, Color.BLACK);
((StyledDocument) textPane.getDocument()).setCharacterAttributes(0, textPane.getDocument().getLength(), set, false);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
panel.add(textPane, gbc);
panel.add(textPane2, gbc);
frame.add(panel);
frame.setSize(500, 400);
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
System.err.println(textPane.getText());
textPane2.setText(textPane.getText());
}
});
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestDifferentStyles().initUI();
}
});
}
}
输出结果(每个JTextPane周围都有黑色边框):
【问题讨论】:
-
必须等待@Stanislav,他有覆盖 Carer、Selections 和 HightLighter 的解决方案,我认为这是关于 UImanager 及其 XxxResources,
-
@mKorbel 好的,谢谢。然后我会等 StanislavL :-)
-
参见 Charles Bell 的
HTMLDocumentEditor,引用 here。 -
@trashgod 实际上我正在重用 Metaphase 编辑器,但他们的 BackgroundAction 很模糊并且无法正常工作,所以我尝试修复它。我在您的示例中找不到
BackgroundColorAction,但 Metaphase 是基于类似的东西。 -
@trashgod 是的(我们不得不对其进行很多调整,不幸的是该项目看起来并不活跃),但是here is the link to the metaphase editor website。感谢您的 cmets 和欢呼 ;-)
标签: java swing background-color jtextpane styleddocument