Sto provando a creare un piccolo HTML-wysiwyg con uno JTextPane
ma non riesco a far funzionare lo BackgroundAction
. Sto usando setCharacterAttributes
su StyledDocument
del JTextPane
ma sembra problematico. La vista è ok ma il Document
non lo è.Il colore di sfondo del testo JTextPane non funziona
Ecco un piccolo codice dimostrativo che illustra il problema. Ci sono 2 JTextPane
:
- ho impostato il colore della mia sfondo del testo nella prima
- posso recuperare il testo del primo
JTextPane
e impostarlo sulla seconda
-> Non mostrano la stessa cosa nonostante abbiano lo stesso testo.
C'è un modo per impostare il colore di sfondo sul testo selezionato corrente e fare in modo che lo JTextPane
indichi un testo HTML aggiornato?
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();
}
});
}
}
Il risultato di uscita (il bordo nero sono attorno a ciascuna JTextPane
):
devono aspettare @Stanislav, ha soluzioni per la sostituzione Carer, selezioni e HightLighter, penso che si tratta di UImanager e le sue XxxResources, – mKorbel
@mKorbel ok grazie. Aspetterò StanislavL quindi :-) –
Vedi anche 'HTMLDocumentEditor 'di Charles Bell, citato [qui] (http://stackoverflow.com/a/5899816/230513). – trashgod