If you want to add a nice touch to your GUI application, center your window on the screen. Not only does this looks much better than having it start up in the default (0, 0) location, but it takes very little coding effort to make this happen. Fortunately for us, there are two methods for doing this, depending on which version of Java you are using. I will show you how to do it both ways.
Archive for the ‘Snippets’ Category
HOW-TO: Java Gradient Backgrounds
Nowadays, if you are developing a GUI application, it looks more “professional” if your window’s background is gradient (i.e. the background fades from light to dark, or dark to light). This gives your application a more polished look and can greatly improve the interface without much effort. Here’s how to do it…
HOW-TO: Retrieve a File’s extension in Java
For some strange reason, there’s no getFileExtension() or getExtension() method in Java’s File class. Of course, that doesn’t mean we can’t do it on our own. All it takes is one line of code!
HOW-TO: Evaluate a Mathematical String Using ScriptEngine
Suppose you have a String containing some mathematical operation(s). For example, we need to perform the following calculation, but for various reasons, the data type is a String: (10*(34+92)-23)/4. Rather than figuring out ways to parse it (e.g. split or some fancy regex), we can use Java’s ScriptEngine to evaluate the function as is.
HOW-TO: Read a Text File Using BufferedReader
As simple as this may seem to experienced Java programmers, I still see many posts in the Java Forums from beginners asking this very question: How do you read a text file line-by-line using a BufferedReader? Let’s find out.
HOW-TO: Save a BufferedImage to Disk
Recently, I showed you how to take a screenshot and display it in a JFrame using Java’s Robot class. What if you wanted to save the image to the disk as a GIF, JPG, or PNG? It’s actually really easy. Let’s find out how!
MD5 and SHA-1 Encryption in Java
Java has a built-in MessageDigest class which makes it easy to implement an MD5 or SHA-1 hash (among others). Both of these algorithms produce one-way hashes (they cannot be changed back to their original form), and they are usually used for encryption and for checking the integrity of files (checksum). Although they are probably deemed partially insecure, they are still very widely used.
HOW-TO: Screen Capture Using Java’s Robot Class
At some point or another, you may come across a time when you need to capture the user’s screen and save it as an image. Maybe you’re making your own “print screen” program, or doing some other image analysis. Regardless, there is a really simple way to capture the user’s screen, and here it is.
HOW-TO: Extract Text from .DOCX file (Word 2007)
I recently had to figure out a way to extract all of the text from a .DOCX file (Word 2007 document) in Java for a project I’m working on. Surprisingly, it’s even easier than extracting text from a regular .DOC file.
