
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Set Style for JTextPane in Java
To set style for text in JTextPane, use setItalic() or setBold() that sets italic or bold style for font respectively.
Following is our JTextPane component −
JTextPane pane = new JTextPane();
Now, use the StyleConstants class to set style for the JTextPane we created above. We have also set the background and foregound color −
SimpleAttributeSet attributeSet = new SimpleAttributeSet(); StyleConstants.setItalic(attributeSet, true); StyleConstants.setForeground(attributeSet, Color.black); StyleConstants.setBackground(attributeSet, Color.orange); pane.setCharacterAttributes(attributeSet, true);
The following is an example to set style for JTextPane −
Example
package my; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.text.BadLocationException; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; public class SwingDemo { public static void main(String args[]) throws BadLocationException { JFrame frame = new JFrame("Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container container = frame.getContentPane(); JTextPane pane = new JTextPane(); SimpleAttributeSet attributeSet = new SimpleAttributeSet(); StyleConstants.setItalic(attributeSet, true); StyleConstants.setForeground(attributeSet, Color.black); StyleConstants.setBackground(attributeSet, Color.orange); pane.setCharacterAttributes(attributeSet, true); pane.setText("We are learning Java and this is a demo text!"); JScrollPane scrollPane = new JScrollPane(pane); container.add(scrollPane, BorderLayout.CENTER); frame.setSize(550, 300); frame.setVisible(true); } }
Output
Advertisements