Converting a mouse position to the caret position of a JTextComponent can be done by using the JTextComponent method viewToModel(). This can be pretty useful if you need to set the caret position of the component when you do a right click of the mouse.

The component can apply to JTextArea, JEditorPane and JTextPane respectively.

Setting the font of either a JEditorPane or JTextPane is not possible by doing it directly. However, you can do that by setting it in the EditorKit class. This post uses the RTFEditorKit class as an example of the editor kit used by a JEditorPane.

I created a custom class that inherits the RTFEditorKit to make things simpler. Just call initializeDefaultFont() to set the font to the JEditorPane. However, a very important thing to note is that this method should only be called after the RTFEditorKit object is set to the JEditorPane.setEditorKit() method. If the initializeDefaultFont() is called before that, the font will not be set.

To use the class. Check the sample code below.

And the MyRTFEditor.java class is below.

Having a JEditorPane support RTF is possible with the use of an editor kit class. In Java’s case, the RTFEditorKit does the trick. When you save RTF files and view them in a text editor, you would see codes that start with \ plus some letters. Only RTF clients understand it. In the JEditorPane’s case, the RTFEditorKit will be the one to convert the RTF code into the JEditorPane’s document and display the same content as what you would see in an RTF client application.

There is no need to call the setText() method of JEditorPane. Once the RTFEditorKit stores and converts the RTF code to String into the javax.swing.text.Document of the JEditorPane, it will automatically be displayed.

The method returns a String just for convenience in case you want to know what the content is. Or, you can call doc.getText(0, doc.getLength()) directly after the RTFEditorKit has finished processing the Document object.

Related Posts Plugin for WordPress, Blogger...