Wednesday, April 17, 2013

Image Viewer program


This is a simple Java image viewer program. You can view an image by selecting the image from the image list. It also allows you to add an image file to the list. The images are store in a text file call imagefiles.txt. You might learn the followings from the program:


-Display a frame window
-Draw image on the frame by using Canvas class
-Add controls to the frame
-Write code for control events
-Read from and Write data to file

ImageViewer source code:

1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4 import javax.swing.event.*;
5 import java.awt.image.*;
6 import javax.swing.filechooser.*;
7 import java.io.*;

8 class ImageBox extends Canvas implements ImageObserver{
9   private Image img;

10   public void paint(Graphics g){
  
            int iw=img.getWidth(null);
            int ih=img.getHeight(null);
            if (iw>800) iw=500;
            if (ih>800) ih=500;
            g.drawImage(img,0,0,iw,ih,this);
           
   }

11 public Image selImage(String filename, Component c){
           
            return(c.getToolkit().getImage(filename));
           
            }
12 public void readImage(String filename){
              img=selImage(filename, this);    
            }
}

13 class  MainInter extends JFrame implements ActionListener,ListSelectionListener{
            JFrame frame;
            JList imglist;
            JButton addbt;
            DefaultListModel listmodel;
            JLabel lbl;
            JScrollPane scr;
            JPanel panel;
            ImageBox imgb;
           
14        MainInter(){
15        frame=new JFrame("Image Viwer");
16        imgb=new ImageBox();
17        listmodel=new DefaultListModel();
18        addbt=new JButton("Add image...");
19        addbt.addActionListener(this);
20        addbt.setBounds(10,350, 100, 30);
21        lbl=new JLabel("<html><font color='blue'>Image List</font></html>");
22        lbl.setBounds(10,3,100,30);
23        addToList(listmodel);
24        imglist=new JList(listmodel);  
25        imglist.setVisibleRowCount(20);
26        imglist.addListSelectionListener(this);
27        frame.setLayout(null);
29        panel=new JPanel();
30        panel.setBounds(10,33,270,300);
31        scr=new JScrollPane(imglist);
32        panel.add(scr);        
33        frame.add(panel); //show the drawing
34        imgb.setBounds(300,33,500,300);
35        frame.add(imgb); //show the drawing
36        frame.add(addbt);
37        frame.add(lbl);
38        frame.setSize(850,450);
39        frame.setResizable(false);
40        //frame.setExtendedState(frame.getExtendedState() | frame.MAXIMIZED_BOTH);
41        frame.addWindowListener(new Listener());
42        frame.setVisible(true);
43        imglist.setSelectedIndex(0);          
            }
44 public void actionPerformed(ActionEvent e){
            if(e.getSource()==addbt) showFileDialog(frame);
           
                       
}

45 public void valueChanged(ListSelectionEvent e){
            loadImage(imglist.getSelectedValue().toString());
           
}

46 public void loadImage(String filename){
            imgb.readImage(filename);           
            imgb.repaint();
            }
47 static class Listener extends WindowAdapter{


 public void windowClosing(WindowEvent event){

            System.exit(0);

                  }

       }
48 public void addToList(DefaultListModel listmodel){
         
  try{ //catch errors if any
            String text;
            FileReader fr=new FileReader("imagefiles.txt");
            BufferedReader br=new BufferedReader(fr);
            while ((text=br.readLine())!=null){
                        //Read  lines of string from the file using readLine() method
                        listmodel.addElement(text);
           
             }
            br.close();//close file using close() method
            fr.close();    
     } catch(Exception ie){System.out.println("IO problem!");ie.printStackTrace();}

  }


49 public static void saveToFile(String filename,String text){
   try{ //catch errors if any
    FileWriter fw=new FileWriter(filename,true); 
     BufferedWriter bw=new BufferedWriter(fw);
     bw.write(text);//write text to the file using write method
     bw.newLine();//new line writing
     bw.flush();//write any buffered text to the file
     bw.close();//close file using close() method  
    }catch(IOException ie){System.out.println("Error in writing to file...");}      
}


50 public void showFileDialog(Frame frame){
    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF Images", "jpg", "gif");
    chooser.setFileFilter(filter);
    int returnVal = chooser.showOpenDialog(frame);
    if(returnVal == JFileChooser.APPROVE_OPTION) {     
            saveToFile("imagefiles.txt",chooser.getSelectedFile().toString());
                         listmodel.addElement(chooser.getSelectedFile().toString());
           
         }
 }

}

51 public class ImageViewer{
 
public static void main(String args[]){
     new MainInter();
  
}


}
Image view program in Java


Code Explanation:
1-7 include classes needed to get frame, controls, image to draw interface and respond to actions, and read and write file.
8 The ImageBox class extends the Canvas class and implements the ImageObserver interface. The Canvas class allows to draw text, graphics,  and image . It is used to show image in this program. The ImageObserver interface is to control the image loads.
9 The img variable is used to store the image to display on the window.
10 The paint method of the Canvas class draws image on the window by using the drawImage method of the Graphics class. I prefer to limit the image with to 500, and height to 500 if these dimensions are greater than 800.
11 The selImage method returns the image file selected by the user (from the list).
12 The readImage method assigns the image file to the img variable. So the image is ready to display on the window.
13 The MainInt class shows the main interface (frame, controls, and image) of the program. The interface of the program composes of one frame (JFrame) to contain other controls, one list box (JList) to diplay a list of image files, one button (JButton) to add an image file to the list, one image box (ImageBox), and one label (JLabel) to display "Image list" about the the list box. The MainInt extends JFrame class and implements ActionListener and ListSelectionListener interfaces. The ActionListener interface contains actionPerformed method to be implemented to perform the action when the button is clicked. The ListSelectionListener interface contains the valueChanged method to be implemented to perform the action when an element of the list box is selected.
14 It is the constructor of the MainInt class. When the object of the MainInt class is created, the code in the constructor block is executed to draw the interface of the program.
15 Create a frame object to contain all other controls.
16 Create ImageBox object. It will be placed in the frame object so that the image is displayed.
17 Create a listmodel object. It is wrapped in JList. It has a methods to add to and remove elements from the JList.
18 Create button object. This button object will be clicked to add image files to the list.
19 Add action listener to the button object so that it is able to react when the user clicks it.
20 Define the location (left, top), and size (width, height) of the button to display on the window.
21 Create a label object to display only "Image list" text above the list of image files.
22 Define the location (left, top), and size (width, height) of the label to display on the window.
23 Populate image files to the the listmodel object.
24 Wrap the listmodel object in the JList imglist object.
25 Define the number of rows (without scrolling) that can be visible in the imglist object.
27 Add list selection listener to the imglist object object so that it is able to react when the user selects its element.
28 Set frame layout to null so that you can place controls in any locations with setBounds method.
29 Create JPanel panel object to contain the imglist object.
30 Define the location (left, top), and size (width, height) of the panel object.
31 Create JScrollPane src object to make the list box scrollable.
32 Add the src object to th panel object.
33 Add panel object on the frame object.
34 Define the location (left, top), and size (width, height) of the ImageBox imgb object.
35 Add imgb object to the frame object.
36 Add button addbt object tot the frame.
37 Add label lbl object to the frame.
38 Set the dimensions (width and height) of the frame to display.
39 Disable frame resizing.
41 Add window listener to the frame object so it is able to cose when the user click the close icon on the top-right corner of the frame window (when the program loads).
42 Make sure the frame is visible to the user.
42 Select the first image file to show.
44 The actionPerformed method works when the user clicks the button. This method is in the ActionListener interface.
45 The valueChanged method works whent the user select an image file to the list box to show.
46 The loadImage method is called to show image on the window each time the user selection an image file from the list box.
47 The class Listener extends WindowAdapter class. The WindowAdapter class has windowClosing method that you can write to exit the program.
48 addToList method is implemented to read image paths (stored in plain text format) from imagefiles.txt file and add them to the list box when the program loads.
49 saveToFile method is implemented to save the image path to the imagefiles.txt file when the user clicks the Add image... button to selected the image file.
50 showFileDialog is implemented to show the file dialog in which the user can choose an image file to add to the list box. This method is invoked when the user clicks the Add image... button.
51 ImageViewer class has the main method to start the program.

5 comments:

  1. I have live camera http://www.kapital3.org:8080/ and u can see "•Simple Page Refreshment" I try add in to my website but don't working.... all index page Refresh..... I need just photo from camera....

    how I can do?

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete