0

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

newSpringer
  • 1,018
  • 10
  • 28
  • 44

2 Answers2

2

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

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • i have changed my TextArea to a JEditorPane, i have added the JAR file for the JSyntaxPane, i have also added the code to change the SyntaxKit in the JEditorPane so the writing like : jEdtTest.setEditorKit(new SyntaxKit("java")); but it is saying cannot find symbol, i need to create a class for the SyntaxKit... do you know why it is saying this? – newSpringer May 22 '12 at 16:49
  • @newSpringer: I know nothing about JSyntaxPane library, sorry - and this probably deserves to be a second question. Can you first try displaying any HTML in `JEditorPane` to make sure it works as expected? – Tomasz Nurkiewicz May 22 '12 at 16:53
  • cheers, i got this to work and it works perfectly... i have edited my answer also just to show how i got it to work, thanks again – newSpringer May 23 '12 at 16:07
0

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

Nate
  • 16,748
  • 5
  • 45
  • 59