The reply of the friend Gui_biem is very good!!
But I’ll leave mine too.
Assuming both classes are in the same package:
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
public class EstiloTextPanel extends JTextPane {
private Style negrito;
private Style italico;
private Style normal;
public EstiloTextPanel(StyledDocument doc) {
super(doc);
initStyles();
}
public EstiloTextPanel() {
super();
initStyles();
}
private void initStyles() {
normal = StyleContext.getDefaultStyleContext().getStyle(
StyleContext.DEFAULT_STYLE);
negrito = getStyledDocument().addStyle("bold", normal);
StyleConstants.setBold(negrito, true);
italico = getStyledDocument().addStyle("italic", normal);
StyleConstants.setItalic(italico, true);
}
public void insertBoldText(String text) throws BadLocationException {
getStyledDocument().insertString(getStyledDocument().getLength(), text,
negrito);
}
public void insertItalicText(String text) throws BadLocationException {
getStyledDocument().insertString(getStyledDocument().getLength(), text,
italico);
}
public void insertNormalText(String text) throws BadLocationException {
getStyledDocument().insertString(getStyledDocument().getLength(), text,
normal);
}
}
and also:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.text.BadLocationException;
public class TestandoEstiloTextPanel extends JFrame {
private EstiloTextPanel verPanel;
public TestandoEstiloTextPanel() throws BadLocationException {
super("FORMATADO");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);
verPanel = new EstiloTextPanel();
add(verPanel, BorderLayout.CENTER);
verPanel.setEditable(false);
verPanel.insertBoldText("Negrito\n");
verPanel.insertItalicText("Itálico\n");
verPanel.insertNormalText("Normal\n");
setVisible(true);
}
public static void main(String[] args) throws BadLocationException {
new TestandoEstiloTextPanel();
}
}