Guides

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
Tweets by imRohit46 ^(http://appsbuilders.org/goto/888)
https://plus.google.com/+Imrohit46Blogspot/posts/

3 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *