I am trying to make a small HTML-wysiwyg with a JTextPane
but I can't get the BackgroundAction
to work. I am using setCharacterAttributes
on the StyledDocument
of the JTextPane
but it seems problematic. The view is ok but the Document
is not.
Here is a small demo code showing the problem. There are 2 JTextPane
:
- I set the background color of my text in the first one
- I retrieve the text of the first
JTextPane
and set it on the second one
--> They don't show the same thing although they have the same text.
Is there a way to set the background color on the current selected text and have the JTextPane
report an updated HTML-text?
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();
}
});
}
}
The output result (the black border are around each JTextPane
):
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…