This is an article on viewing images in Java where I’ll take you through the steps of creating a viewer. This will give you a very basic Java Viewer you can use to view images. The tutorial is based on our Java Image Viewer that you will need our JDeli jar downloaded to use the JDeli viewer, why not go check it out!
Creating the class
To create a simple viewer we will need to have a menu, a file selector and a window to view the image.
First, we will start by creating a class called Viewer that extends JFrame and a method run that will be called from the constructor.
public class Viewer extends JFrame {
|
We have used Java.awt.ToolKit class to get the width and height of the screen. These will be used to set the frame size as well as the image size later on. I have set my viewer name to “Image Viewer” but feel free to change the name.
I have chosen to have a larger viewer by subtracting 100 from the width and height of the screen, but you can play around with what size you may want.
Adding the panel for displaying the image
Now that we have a frame we will want to add a Panel and a label, this will be where the image is displayed. You’ll want to put the Image label in a scroll pane so that you can scroll the image up and down. This can be done by adding the following to the run method:
|
I have set the image label bounds to the screen width and height minus 200 but you can change these values to how large or small you want to image to be.
Adding the menu
As you can see we call the addMenu() method above, we will need to create this method to be able to open files.
Create the JMenuItem open as a global variable as we will need to use this later on.
|
Here we create our menu bar and items and add them in and set the JMenuBar for the frame.
Adding functionality to the menu
For this, we want to ensure that the Viewer class implements ActionListener. This is so we can open a file when the menu item is clicked. Therefore we will need to override this method:
|
Finally, we will then need to make the openFile method that is being called above. This method will open a file chooser and use the file selected to set the icon in the imageLabel variable.
|
Now when we run the code we should hopefully have something that looks like this:
Next steps
Once you have images displaying, this is just the start. It is very easy to add processing features, annotations and special effects. If you check out our Java image viewer you will see lots of ideas! If you have any cool suggestions, please do post your ideas and I may well write a follow-up.