How to use JTextPane to style code in Java?



To style code in a TextPane component use the setText() for text and work with HTML tags. For code, use the <code> tag. Also, do not forget to set the content type to “text/html” −

JTextPane pane = new JTextPane(); pane.setContentType("text/html");

If you won’t set the content type, then the output will display all these HTML tags inside the JTextPane. Now, set the code inside <code> −

pane.setText("<HTML><BODY><CODE> #include <iostream>; <br> using namespace std; <br>main() {<br>cout << \"Hello World\";<br>   return 0;<br>}</CODE><br></BODY></HTML>");

The following is an example wherein we will be displaying a code in the JTextPane. The code we are styling here is a sample C++ code −

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; 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();       pane.setContentType("text/html");       pane.setText("<HTML><BODY><CODE> #include <iostream>; <br> using namespace std; <br>main() {<br>cout << \"Hello World\";<br>   return 0;<br>}</CODE><br></BODY></HTML>");       JScrollPane scrollPane = new JScrollPane(pane);       container.add(scrollPane, BorderLayout.CENTER);       frame.setSize(550, 300);       frame.setVisible(true);    } }

The output is as follows. Displays the C++ code in the correct format in a JTextPane −

Output

Updated on: 2019-07-30T22:30:26+05:30

727 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements