JAVA中的GUI,用于在同一帧中显示不同的图像

时间:2014-03-17 19:37:24

标签: java user-interface jframe jlabel imageicon

我想在循环内的同一帧中显示不同的图像。 String pathName []包含图像的不同路径。运行此代码时,只有最后一张图像,即路径路径名[last]的图像才会显示在帧上,而我希望所有图像以连续的方式显示(延迟为1秒)。感谢帮助。

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();
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您的问题很常见:​​您在事件线程上的Swing GUI中调用Thread.sleep(...),从而实际上使整个GUI处于休眠状态。

解决方案:Google使用Swing Timer并使用它来代替你的while循环/ Thread.sleep(...)

另外,如果图像不是太大,那么考虑一次读取它们(在后台线程中),将它们放入ImageIcons,然后在Swing中交换JLabel的ImageIconsand计时器。

例如,您可以执行以下操作:

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
}

别处:

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();
  • 注意:代码未编译或测试,仅作为要考虑的步骤的一般示例发布。