Search code examples
javauser-interfacejframejlabelimageicon

GUI in JAVA to display different images in a same frame


I want to display different images in a same frame within a loop. String pathName[] contains the different paths of the images. When running this code, only last image i.e image at path pathname[last] is getting displayed on frame instead I want all images to be displayed in a continuous way (have given delay of 1sec ). Help is appreciated.

public void actionPerformed(ActionEvent event) {

    int i=0;
    while(i<5){
        if(i>0){
            Container labelParent = receiverImageLabel.getParent();
            labelParent.remove(receiverImageLabel);
            labelParent.validate();
            labelParent.repaint();
        }

        try {
            imageR = ImageIO.read(new File(pathName[i++])).getScaledInstance(512,512 , BufferedImage.SCALE_SMOOTH);
            receivedImage = new ImageIcon(imageR);
        }catch (IOException e) {
            e.printStackTrace();
        }
        receiverImageLabel = new JLabel(receivedImage);
        receiverFrame.getContentPane().add(BorderLayout.EAST,receiverImageLabel);
        receiverFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        receiverFrame.setSize(800,700);
        receiverFrame.setVisible(true);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Solution

  • Your problem is a common one: you're calling Thread.sleep(...) in a Swing GUI on the event thread and are essentially thus putting the entire GUI to sleep.

    Solution: Google the Swing Timer and use this in place of your while loop/Thread.sleep(...)

    Also, if the images aren't too big, then consider reading them all in at once (in a background thread), putting them into ImageIcons, and then swapping out a JLabel's ImageIconsand in your Swing Timer.

    For example, you could do something like:

    ImageIcon[] icons = new ImageIcon[IMAGE_COUNT];
    for (int i = 0; i < IMAGE_COUNT; i++) {
      BufferedImage img = ImageIO.read(...); // read in the appropriate image
      // ...... here manipulate the image if desired such as re-size it
      icons[i] = new ImageIcon(img);  // put it into an icon
    }
    

    elsewhere:

    int timerDelay = 1000;
    new Timer(timerDelay, new ActionListener(){
      int count = 0;
    
      @Override
      public void actionPerformed(ActionEvent e) {
        if (count < IMAGE_COUNT) {
          someLabel.setIcon(icons[count]);
          count++;
        } else {
          // stop the timer
          ((Timer)e.getSource()).stop();
        }
    
      }
    }).start();
    
    • Note: code not compiled nor tested and is posted only as a general example of steps to consider.