In this section, we are going to show you how to create a TextEditor using SWT in Java.
In SWT, the classes ToolBar and ToolItem are allowed to create the TextEditor. The class ToolBar provides the toolBar items and the class ToolItem adds the item to the toolbar. The method setText() of class ToolItem sets the string specified and the method addListener() calls the Event class to perform the action on the ToolItem.
In this example the class StyledText is used to display and edit the text and the method styledText.copy() copies the selected text to the clipboard. The method styledText.cut() is used to moves the selected text to the clipboard. Apart from this styledText.paste() method is defined to replaces the selection with the text on the clipboard. The method setText() sets the specified content and the method setFont() sets the specified font to render the text.
We have defined a variable unsaved of Boolean type to check whether there is any change after saving. The method saveChanges() is created to save the unsaved changes before discarding the text. To display the alert message, MessageBox is used.
The method loadText() is created to load the text from the selected file. For this, we have used the class BufferedReader to read the file. The method styledText.setText(buffer.toString()) sets the content by converting the data of StringBuffer into string.
The method saveText() is created to save the content of the StyledText to the file. In this method, the FileWriter class writes the content of StyledText. The class FileDialog is used to navigate the file system and and allows to select or enter a file name.
Here is the code of TextEditor.java
Output will be displayed as
Liked it! Share this Tutorial