This is a small utility class that I often reuse to read values from an XML file. It uses Java’s built-in XML parsing but implements two basic yet useful methods so that the logic is abstracted away: getElementValue() and getElementValues().
Wrapping Strings
Having the ability to wrap strings can be useful if you don’t know how long your strings are going to be, such as when you’re using translated text in a JOptionPane (or any other GUI element for that matter). This is nice utility class that does exactly what we need — StringWrapper.
Java Relative Date and Time
I recently needed the ability to show the date and time in a relative manner. I.e., rather than display the full date and time like “August 13, 2009 at 3:07 pm”, I wanted to determine what the given date is relative to now and instead show something like “one hour ago” or “one hour from now.” This class converts a Calendar or Date object into a String representing the relative date.
Save User Preferences with Java’s Preferences API
Java’s Preferences API is an easy way to save user preferences for your application without having to manually write/read a config file. This method is also platform independent so we don’t necessarily have to worry about where/how the data is saved or whether or not you have permission to do so.
Centering a JFrame
It usually looks nicer to have your application start up in the center of the user’s screen rather than at the (0,0) coordinate. There are two methods to do this depending on which version of Java you’re using.
Detect link clicks in JEditorPane
If you’re using a JEditorPane to display HTML that potentially contains hyperlinks, there is no built-in function to automatically detect if the user clicks on a link. Creating a HyperlinkListener will solve the problem.
Gradient JPanel Backgrounds
Using gradient backgrounds in your application creates a clean and polished look. Doing so can really help improve the interface without too much effort.
Java File Extensions
In dealing with files, you’ll realize that there isn’t a method to get the extension which you sometimes need to appropriately handle certain file types.
Levenshtein Distance Algorithm
For an anti-plagiarism application, I needed a way to calculate the similarity between two strings. I wasn’t sure how to go about doing this at first, but then I came across the Levenshtein Distance Algorithm which gets the job done well (for strings that aren’t too long).
JLabel Hyperlink
Since there isn’t a JHyperlink class in Java Swing, I made one by extending JLabel.
