Question

I'm trying to BOLD the text in JPane but it not working. If it ITALIC or UNDERLINE its working fine. Below is my code.

String strText = "<b><i><u>Testing</b></i></u>";
javax.swing.text.Style style1 = jTextPane1.addStyle("I'm a Style", null);
StyleConstants.setForeground(style1, Color.BLACK);
StyleConstants.setFontSize(style1, 15);
StyleConstants.setFontFamily(style1, "Arial Unicode MS");
if(strText.contains("<b>"))
                        {
                            StyleConstants.setBold(style1, true);
                            strText = strText.replace("<b>", " ");
                            strText = strText.replace("</b>", " ");

                        }
                        if(strText.contains("<i>"))
                        {
                            StyleConstants.setItalic(style1, true);
                            strText = strText.replace("<i>", " ");
                            strText = strText.replace("</i>", " ");

                        }
                        if(strText.contains("<u>"))
                        {
                            StyleConstants.setUnderline(style1, true);
                            strText = strText.replace("<u>", " ");
                            strText = strText.replace("</u>", " ");

                        }
try {
strText = strText.trim();
doc.insertString(doc.getLength(), strText, style1);
} 

The UNDERLINE and ITALIC working fine meanwhile BOLD not working as per expected. The text not BOLDED. Please advice where i did mistakes.

Était-ce utile?

La solution

Based on this example, the fragment below illustrates three related styles based on the same font and size:

image

SimpleAttributeSet normal = new SimpleAttributeSet();
StyleConstants.setFontFamily(normal, "SansSerif");
StyleConstants.setFontSize(normal, 16);

SimpleAttributeSet bold = new SimpleAttributeSet(normal);
StyleConstants.setBold(bold, true);

SimpleAttributeSet italic = new SimpleAttributeSet(normal);
StyleConstants.setItalic(italic, true);

doc.insertString(doc.getLength(), s + "\n", normal);
doc.insertString(doc.getLength(), s + "\n", bold);
doc.insertString(doc.getLength(), s + "\n", italic);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top