Build Image Viewer Application using Java



A simple image viewer app using java for beginners.

Source Code:
———————-
import javax.swing.*;
import java.io.*;
import java.awt.event.*;

public class ImageViewer {

public static void main(String[] args) {

JFrame frame = new ImageViewerFrame();
frame.setTitle(“Image Viewer App”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

});
}

}

@SuppressWarnings(“serial”)
//A frame with a label to show an image
class ImageViewerFrame extends JFrame {

JLabel label;
JFileChooser chooser;
JMenuBar menubar;
JMenu menu;
JMenuItem open;
JMenuItem exit;

//Constructor
public ImageViewerFrame() {

setSize(500,500);

//Use a label to display the image
label = new JLabel();
add(label);

//Set up the file chooser
chooser = new JFileChooser();
chooser.setCurrentDirectory(new File(“.”));

//set up the menubar
menubar = new JMenuBar();
setJMenuBar(menubar);

menu = new JMenu(“File”);
menubar.add(menu);

open = new JMenuItem(“Open”);
menu.add(open);

open.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent event) {

//show file chooser dialog
int result = chooser.showOpenDialog(null);

//if file selected, set it as icon of label
if(result == JFileChooser.APPROVE_OPTION) {
String name = chooser.getSelectedFile().getPath();
label.setIcon(new ImageIcon(name));
}
}
});
}

}
———————————————————————————

HTML Tutorials: https://www.youtube.com/playlist?list=PLwPDdNxG2EFcU85DtejxG0zGYuO3ivLdR

Follow me:
——————
https://www.facebook.com/imrohit46

https://plus.google.com/+Imrohit46Blogspot/posts/

3 thoughts on “Build Image Viewer Application using Java”

  1. I have followed your tutorial and the program works for JPG and PNG files. How should it be modified to work with BMP files? Thanks!

    Reply
  2. How to add multiple images side by side on a single panel within a single window/frame?? Plz send source code for the same

    Reply

Leave a Comment