Here is a macro that inserts the path of the current buffer in the text:
String newText = buffer.getPath(); textArea.setSelectedText(newText); |
Unlike in our first macro example, here we are calling class methods on particular objects. First, we call getPath() on the current Buffer object to get the full path of the text file currently being edited. Next, we call setSelectedText() on the current text display component, specifying the text to be inserted as a parameter.
In precise terms, the setSelectedText() method substitutes the contents of the String parameter for a range of selected text that includes the current caret position. If no text is selected at the caret position, the effect of this operation is simply to insert the new text at that position.
Here's a few alternatives to the full file path that you could use to insert various useful things:
// the file name (without full path) String newText = buffer.getName(); // today's date import java.text.DateFormat; String newText = DateFormat.getDateInstance() .format(new Date()); // a line count for the current buffer String newText = "This file contains " + textArea.getLineCount() + " lines."; |
Here are brief comments on each:
In the first, the call to getName() invokes another method of the Buffer class.
The syntax of the second example chains the results of several methods. You could write it this way:
import java.text.DateFormat; Date d = new Date(); DateFormat df = DateFormat.getDateInstance(); String result = df.format(d); |
Taking the pieces in order:
A Java Date object is created using the new keyword. The empty parenthesis after Date signify a call on the constructor method of Date having no parameters; here, a Date is created representing the current date and time.
DateFormat.getDateInstance() is a static method that creates and returns a DateFormat object. As the name implies, DateFormat is a Java class that takes Date objects and produces readable text. The method getDateInstance() returns a DateFormat object that parses and formats dates. It will use the default locale or text format specified in the user's Java installation.
Finally, DateFormat.format() is called on the new DateFormat object using the Date object as a parameter. The result is a String containing the date in the default locale.
Note that the Date class is contained in the java.util package, so an explicit import statement is not required. However, DateFormat is part of the java.text package, which is not automatically imported, so an explicit import statement must be used.
The third example shows three items of note:
getLineCount() is a method in jEdit's JEditTextArea class. It returns an int representing the number of lines in the current text buffer. We call it on textArea, the pre-defined, current JEditTextArea object.
The use of the + operator (which can be chained, as here) appends objects and string literals to return a single, concatenated String.