newSpringer
newSpringer

Reputation: 1028

Java: How to pretty print .java file

I have a JTextArea, and I have this being populated with a chosen .java file, the problem is that the file is appearing as just normal text. I would like to add some pretty print so that the user will be able to see the file as if the file was open in eclipse (keywords different color, comments will be in grey... etc)

I have not been able to find any good examples online for how to do this. what would be the best way to do this?

EDIT:

I got this to finally work, i added the JSyntaxPane jar file to my classpath (jsyntaxpane-0.9.5-b29.jar to be exact) then i added the following two lines of code to get it working for my JEditorPane.

jsyntaxpane.DefaultSyntaxKit.initKit();
JEditorPane.setContentType("text/java");

This can also be used on the following languages: JavaScript, Properties, Groovy, C, C++, XML, SQL, Ruby and Python... just by simply changing text/java to text/LANGUAGE_YOU_WANT in the above code

Upvotes: 0

Views: 910

Answers (2)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

JTextArea can only display plain text (like notepad in Windows). If you want to show pretty printed source code with colors, you need JEditorPane, which allows you to display HTML.

Now you can either generate HTML manually with syntax-highlighted Java source code or use some library.

See also

Upvotes: 2

Nate
Nate

Reputation: 16898

JEdit-Syntax has a JEditTextArea class that will do syntax highlighting. This project was spun off to package some subcomponents of the JEdit project.

Upvotes: 0

Related Questions