- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to insert styled text in a JTextPane Component
Insert styled text in a JTextPane component using the SimpleAttributeSet and StyleConstants classes. With that, we will also use StyledDocument.
The following is an example to insert styled text in a JTextPane component −
package my; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Font; 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.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; 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 textPane = new JTextPane(); textPane.setForeground(Color.blue); textPane.setBackground(Color.cyan); SimpleAttributeSet set = new SimpleAttributeSet(); StyleConstants.setItalic(set, true); textPane.setCharacterAttributes(set, true); textPane.setText("This is our text pane! "); Font font = new Font("Verdana", Font.BOLD, 18); textPane.setFont(font); StyledDocument doc = (StyledDocument) textPane.getDocument(); Style style = doc.addStyle("StyleName", null); StyleConstants.setBold(style, true); doc.insertString(doc.getLength(), "Demo text", style); JScrollPane scrollPane = new JScrollPane(textPane); scrollPane = new JScrollPane(textPane); container.add(scrollPane, BorderLayout.CENTER); frame.setSize(550, 300); frame.setVisible(true); } }
Output
Advertisements