Java enum
February 9th, 2009
One of the cooler features introduced in JDK 1.5 was the enum keyword.
In short, an enum is a collection of constant values. They provide a simple way of limiting the options you can use for a variable if there are only a standard, or in other words enumerated, set of values it can be.
For instance, imagine if you were modeling a deck of cards. Each card would be one of 4 possible suits: clubs, diamonds, spades, or hearts. One option is to store the suit in a string variable, however this is cumbersome for two reasons:
- There has to be careful validation in the setter for the suit to ensure only the four possible suits are allowed, taking into account the capitalization of the string.
- If you needed to do different handling based on the suit, if/elses would have to be used; a switch statement cannot be used on strings.
Instead of using a string to track the suit, an enum is a good candidate. An enum is defined just like a class except using the enum keyword instead of class. Also like a class, an enum is typically defined in its own file of the same name.
1 2 3 | public enum Suit { HEARTS, CLUBS, SPADES, DIAMONDS } |
A simple enum, which is usually sufficient, just lists the possible values. Since these values are effectively constant, the convention is the same as for final variables (all caps).
Using an enum is the same as any other object:
1 2 3 4 5 6 7 8 9 10 11 | public class Card { private Suit suit; public Suit getSuit() { return suit; } public void setSuit(Suit s) { suit = s; } } |
When attempting to set a suit on a card, the compiler will only allow one of the four values defined in the enum, so there is no need to add validation in the setter. The value is accessed by using the enum name and the value name, similar to calling a static method or variable:
1 2 | Card card = new Card(); card.setSuit(Suit.DIAMONDS); |
If for some reason, we needed to do different handling based on suit (not an overly applicable scenario in this use case, but often a common usage of enums), enums are supported in switch statements:
1 2 3 4 5 6 7 8 | switch (myVariable) { case Suit.HEARTS: // do hearts processing break; case Suit.CLUBS: // do clubs processing break; } |
Keep in mind that an enum can also take on other properties of a class. Instance variables and methods can still be defined in the enum. Since the only creation of enum values are done inside of the enum itself, any instance variables must be initialized in the constructor. For example, assume we wanted a display name for each suit. The following changes would support this addition:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public enum Suit { HEARTS("Hearts"), DIAMONDS("Diamonds"), CLUBS("Clubs), SPADES("Spades"); private String name; private Suit(String n) { name = n; } public String getName() { return name; } } |
Given the above changes, the public methods can be called on the enum values as if they were any other object::
1 | System.out.println(Suit.HEARTS.getName()); |
For another example, check out the enum for each column in the grades table in CodeTurtle.
Right-Clicking Tables in Swing
January 2nd, 2009
A lot of the data in CodeTurtle is tabular. Inevitably, I ended up wanting to have a right-click menu for operations on a particular row. The problem is, the default behavior for a JTable doesn’t automatically select the row under the cursor on a right-click. After a bit of poking around, the solution was pretty simple. The following example is a mouse adapter assigned to the table itself. The purpose of this particular implementation is to display a popup menu under the cursor for operations on the selected row. This code allows the user to right-click any row to both select it and then display the menu of operations to execute against it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | private class PopupMenuListener extends MouseAdapter { public void mousePressed(MouseEvent e) { showPopup(e); } public void mouseReleased(MouseEvent e) { showPopup(e); } private void showPopup(MouseEvent e) { if (e.isPopupTrigger()) { // Select the row under the cursor so we know // which to edit or delete Point p = e.getPoint(); int rowNumber = rowAtPoint(p); ListSelectionModel model = getSelectionModel(); model.setSelectionInterval(rowNumber, rowNumber); // Display the popup popupMenu.show(e.getComponent(), e.getX(), e.getY()); } } } |
This can be seen in action (at least as of the time of writing) in the CommentsTable.java file.
Code Sample: File Chooser Demo v1.0
November 2nd, 2008
Swing provides built in support for a file chooser dialog. It’s a huge time saver to not have to implement all of the pieces involved, the component is pretty well flushed out, and it’s easy to use.
The attached code is released under the GNU General Public License.
Code Sample: Dialog Boxes Demo v1.0
November 1st, 2008
Swing includes some quick and powerful methods to facilitate the display of dialog boxes. These dialog boxes can be customized with a message, title, icon, and even the choice of buttons to display to the user. Additionally, the dialog boxes can even request user input in the form of a text field or drop-down box. The boxes are modal, which means that their parent frame cannot be accessed until the dialog box is addressed.
This code sample demonstrates a few different possibilities for working with dialog boxes. When running the application, a simple frame will appear with a button for each example. Pressing the button will result in its corresponding dialog box being displayed. In certain cases, logging information will be written to standard output to reflect the user’s interaction with a dialog box.
The attached code is released under the GNU General Public License.
Command Line Compiling
October 30th, 2008
One of my students has been using an interesting approach to compiling multiple Java source files from the command line. He keeps a file (named files.txt, but the name is arbitrary) that contains a list of all source files he wants compiled. For instance, an example of its contents might be:
1 2 3 4 5 | ./src/com/redhat/Foo.java ./src/com/redhat/Bar.java ./test/com/redhat/test/FooTest.java ./test/com/redhat/test/BarTest.java |
To compile the project, he specifies to use the following command:
1 | javac -d ./bin @files.txt |
That call will compile each file listed in files.txt and put the compiled class file into a directory named bin. Note that bin must exist prior to the call.
This has the added benefit of being able to simply omit specific files from compilation. For instance, if you have a Java class that’s not finished or in a state that will compile, simply removing it from the files.txt file will allow the rest of the application to be easily compiled.
Exceptions Mini-Lecture – Part 3
October 22nd, 2008
Exceptions are actually just a subset of all of the things that can go wrong in a Java application. There is a distinction between exceptions and errors. These two concepts collectively are modeled through the Throwable class.
Throwable
At the root of the error class hierarchy is the Throwable class. This sits above both errors and exceptions. As such, it is possible to have a catch block catch Throwable. This is typically not correct, for reasons we will see in discussing errors below. However, there are times when the caller would want to prevent any sort of error from bubbling up. In such cases, catching Throwable will prevent any errors at all from bubbling up the call chain.
There are two direct subclasses to Throwable that model the error distinction in Java: Exception and Error.
Error
As taken from the Java API: “An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.” Put another way, errors are generally things the application cannot hope to recover from. As such, it’s generally a bad practice to catch an error, since a catch statement indicates a recovery from an error condition.
One example is the OutOfMemoryError. There is little the application can do to recover when the virtual machine runs out of memory. Therefore, it is usually best to let this error bubble up to the calling method to be treated as a bug.
Exception
Much more common are exceptions, which represent a state that can likely be recovered from by the calling method. For example, a FileNotFoundException is not fatal to the program; the calling code can reprompt the user for the file name. Similarly, an IOException is likely not a fatal error either; the connection can be attempted again after a set period of time or after some configuration changes.
Exceptions are divided into two different types:
Checked
A checked exception must be handled at compile time. As per the first part of this series, handling a checked exception can be down by declaring the calling method throws the exception up to its caller or by catching the exception in a try/catch block.
Unchecked
Unchecked exceptions do not explicitly need to be handled. They may still occur, however the calling method does not have to provide a means for handling them. The calling method may catch an unchecked exception like any other, but it is not required.
Unchecked exceptions are all exceptions that are subclasses of the RuntimeException class. The RuntimeException class itself is a subclass of Exception. Thus, I typically have been saying “most” exceptions when referring to checked exceptions, while this small subset of the class hierarchy below Exception are considered unchecked and behave slightly differently.
Exceptions Mini-Lecture – Part 2
October 22nd, 2008
I wanted to provide an example of the try/catch block introduced in part 1 of the series.
1 2 3 4 5 6 7 8 9 10 11 | try { System.out.println("Correct 1"); foo(); System.out.println("Correct 2"); bar(); System.out.println("Correct 3"); } catch (Exception e) { System.out.println("Error"); } System.out.println("End"); |
Given the above code, what will be printed in the following circumstances?
1.) foo() throws an exception
2.) bar() throws an exception
3.) no exceptions are thrown
Answers are provided after the jump.

