Wednesday, August 6, 2014

Loading images dynamically

The complete code for this, and the images I used are available at https://github.com/spconger/DynamicallyShowImages

To load images I ended up using these imports

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

I sat the image path as a constant. You will have to change the path to make the sample work. To get an easier more flexible path you might try using .getAbsolutePath(), .getPath(), or .getCanonicalPath().

private final String IMG_PATH = "C:\\Users\\stevec\\Workspace\\ImageTest\\Images\\";
private final int IMAGE_WIDTH=315;
private final int IMAGE_HEIGHT=670;

The image is stored in a label using an icon property.(I put the image names in an array).

 BufferedImage img=null;

img = ImageIO.read(new File(IMG_PATH + pictures[i]));
ImageIcon icon = new ImageIcon(img);
JLabel label = new JLabel(icon);

The program starts by letting the user enter how many pictures they want to display. In this case the only valid numbers are 1 to 5. I did not validation. It will crash if you enter any number greater than 5. When they click the button, the action listener, loops for as many times as the user requested, adding labels and pictures to a picturePanel. Then the panel is added to a JPanel that uses a border layout. The frame is given a new size based on the number of images and the image width. Then the frame is revalidated and repainted. These two methods are necessary to redraw the fram with the new picture panel and pictures. Here is the code for the ActionListener.

private class PictureListener implements ActionListener{

@Override
public void actionPerformed(ActionEvent arg0) {
 number = Integer.parseInt(numberField.getText());
 String[] pictures = new String[] {"One.png", "Two.png",
                     "Three.png", "four.png", "Five.png"};
 picturePanel=new JPanel();
 picturePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
 BufferedImage img=null;
 try {
      for (int i=0; i<number;i++){
  img = ImageIO.read(new File(IMG_PATH + pictures[i]));
  ImageIcon icon = new ImageIcon(img);
         JLabel label = new JLabel(icon);
         picturePanel.add(label,BorderLayout.WEST);
           
     }
            panel.add(picturePanel, BorderLayout.CENTER);
     frame.setBounds(200,200,number *(IMAGE_WIDTH),IMAGE_HEIGHT);
     
     frame.revalidate();
     frame.repaint();
 } catch (IOException e) {
     
  e.printStackTrace();
     
    }
     }
  
}

The try catch is required because whenever you try to get a file it might cause an IOException--i.e. the file might not be found.

Here are two pictures of the program running

No comments:

Post a Comment