Making a single line bold in a JTextPane without using HTML
I'm t开发者_C百科rying to bold a single line in my JTextPane, but nothing I do is working. I've tried writing the line with a new, bolded font, but it didn't help.
Font font = new Font("Consolas", Font.BOLD, 11);
textPane.setFont(font);
textPane.setText(textPane.getText() + "\n" + getTimeStamp() + sender + ": " + message);
textPane.setFont(defaultFont);
How can I do this?
The easiest way to do this, is to get the StyledDocument from the JTextPane, and to use the setCharacterAttributes() method.
The setCharacterAttributes method on the StyledDocument object allows you to set for a specific character range, a set of attributes, which can include BOLD.
See the Javadoc for more info
Some sample code could be
// set chars 4 to 10 to Bold
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setBold(sas, true);
textPane.getStyledDocument().setCharacterAttributes(4, 6, sas, false);
Something to watch out for is to ensure that the font family you use actually has a bold font on your system. I started out using Monaco (on OSX) which only includes a regular font. Nothing worked until I switched to Menlo, which had a Menlo Bold entry.
Here is some code based on Oracle's example.
StyledDocument document = textPane.getStyledDocument ();
Style defaultStyle =
StyleContext.getDefaultStyleContext ().getStyle (StyleContext.DEFAULT_STYLE);
Style regular = document.addStyle ("regular", defaultStyle);
StyleConstants.setBackground (regular, backgroundColor);
StyleConstants.setFontFamily (regular, "Menlo");
StyleConstants.setFontSize (regular, 14);
blackStyle = document.addStyle ("BlackStyle", regular);
StyleConstants.setForeground (blackStyle, Color.black);
redStyle = document.addStyle ("RedStyle", regular);
StyleConstants.setForeground (redStyle, Color.red);
StyleConstants.setBold (redStyle, true);
精彩评论