java - JAVA中的GUI在同一帧中显示不同的图像

标签 java user-interface jframe jlabel imageicon

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

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

最佳答案

您的问题很常见:​​您在事件线程上的 Swing GUI 中调用 Thread.sleep(...) 并且实质上因此使整个 GUI 进入休眠状态。

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

此外,如果图像不是太大,则考虑一次全部读取它们(在后台线程中),将它们放入 ImageIcons,然后在 Swing Timer 中换出 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();
  • 注意:代码未经编译或测试,仅作为要考虑的步骤的一般示例发布。

关于java - JAVA中的GUI在同一帧中显示不同的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22463758/

相关文章:

java - JTable 不显示表头

java - 使用 JFrame 在 JPanel 之间切换

java - JFrame 图像,在其上绘画

java - 如何使用 gmail OAuth 验证 IMAP?

java - lucene中精确度和召回率测量的问题

python - 按下按钮时显示一组重复图像的简单图形用户界面

Java JFrame 循环更新

java - 从 Android 路径加载 XML 字符串数组

java - 如何将 json 数据从主报表传递到子报表 Jaspersoft Studio

android - 在多行上添加多个 TextView