Thursday, January 27, 2005

Tip: Editor Abbreviations

WARNING: This blog entry was imported from my old blog on blogs.sun.com (which used different blogging software), so formatting and links may not be correct.


You might have used Code Clips already, since they're featured prominently
in the various Creator

tutorials
.



However, the editor has another less visible feature called "abbreviations".
You can define code fragments which are automatically inserted into the
document at the caret position when you type the abbreviation's name
followed by the space character.



One such useful abbreviation is one to insert a try/catch
block. When writing code in your Creator Java files, you're often dealing with
database related calls, which might throw exceptions, so you need to catch them.
You also want to send the exception message to the log file so you can figure out
what went wrong. To do that, you have to add a
try/catch block to your code. Creator has an
abbreviation for that, named "trc" (for try/catch). Just
type in the four keystrokes [t], [r], [c], [space], and your editor
will go from






to (as soon as you hit space):






Voila! Notice that it puts your caret in the right place too (and that
the original abbreviation name, trc, is gone.)



Here are some other abbreviations you can try: fori to add
a for loop, and
sout for System.out.println("").
You can easily add your own abbreviations too, or, change
the existing ones. The following screenshot shows you everything you
need to know:







  • You open the Tools | Options dialog, drill down to
    the Java Editor, and locate the Abbreviations item on the
    right. Click the ... button to open the customizer.

  • This will show a list of your abbreviations which you can edit,
    or study to learn some of the existing ones if you want to use
    them.

  • When you edit an abbreviation you get to write the code fragment
    that will be inserted. Use the vertical bar ( | ) to
    indicate where the caret position should be after the abbreviation
    substitution. For example, the try catch abbreviation looks like
    this:

    try {
    |
    } catch (Exception ex) {
    log("Error Description", ex);
    }





If you come up with some really useful ones, let us know and we'll add
them to the builtin default abbreviations.


1 comment: