我正在尝试使用
输出结果(每个
JTextPane
制作一个小型的HTML所见即所得编辑器,但我无法使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
周围都有黑色边框):
![output result](https://istack.dev59.com/nAM9e.webp)
HTMLDocumentEditor
,引用此处。 - trashgodMetaphase Editor
,在这里引用链接。你可以在这个问题中链接到它,以供将来的访问者使用。 - trashgod