Skip to content

Instantly share code, notes, and snippets.

@hadinajafi
Created April 23, 2020 16:43
Show Gist options
  • Save hadinajafi/f64ed7652655ac64ae219decc6494f6d to your computer and use it in GitHub Desktop.
Save hadinajafi/f64ed7652655ac64ae219decc6494f6d to your computer and use it in GitHub Desktop.
How to use Styles in Java Swing JTextPane
StyledDocument sd = (StyledDocument) jTextPane.getDocument(); //get the styled document
SimpleAttributeSet boldBlue = new SimpleAttributeSet(); //a bold, blue color, with font attribute creation
StyleConstants.setBold(boldBlue, true); //set it bold
StyleConstants.setForeground(boldBlue, Color.blue); //set the attribute color
jTextPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); //RTL support
StyleConstants.setFontFamily(boldBlue, "Mikhak Light"); //custom font
String text = jTextPane.getSelectedText(); //get selected text in the Editor
try {
jTextPane1.replaceSelection("");
sd.insertString(jTextPane.getCaretPosition(), text, boldBlue);
} catch (BadLocationException ex) {
ex.printStackTrace();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment