2015-10-02 47 views
0

刷新我写出在某些目录中的JFrame图像的代码。 Jframe将一次显示一个图像。图像不能在JFrame中

我的代码表明Jframe的尺寸改变,但图像不会改变。 我把重新验证和油漆,但图像没有刷新。

这里是updateFrame功能,其具有更新的逻辑。

private void updateFrame(JFrame f, String billBoardImageFileLocation, int imageNumber) throws ClassNotFoundException, IOException { 
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); //this is your screen size 
    File folder = new File(billBoardImageFileLocation); 
    String[] extensions = new String[]{"jpeg", "jpg"}; 
    List<File> imageFiles = (List<File>) FileUtils.listFiles(folder, extensions, false); 
    ImageIcon image = new ImageIcon(ImageIO.read(imageFiles.get(imageNumber % imageFiles.size()))); //imports the image 

    if (isDebug.equals("Y")) { 
     System.out.println("Files:" + imageFiles.get(imageNumber % imageFiles.size()).getAbsolutePath()); 
    } 

    JLabel lbl = new JLabel(image); //puts the image into a jlabel\ 
      f.getContentPane().add(lbl); //puts label inside the jframe 
    f.setSize(image.getIconWidth(), image.getIconHeight()); //gets h and w of image and sets jframe to the size 
    f.getContentPane().revalidate(); 
    int x = (screenSize.width - f.getSize().width)/2; //These two lines are the dimensions 
    int y = (screenSize.height - f.getSize().height)/2; //of the center of the screen 
    f.setLocation(x, y); //sets the location of the jframe 
    f.setVisible(true); //makes the jframe visible 
    f.revalidate(); // **** added **** 
    f.repaint(); 
    f.getContentPane().revalidate(); 
    f.getContentPane().repaint(); 
} 

这就是我如何调用updateFrame函数。

try 
{ 
    pProcess = pb.start(); 
    if (showBillBoard.toUpperCase().equals("Y")) { 
     ProcMon proMon = new ProcMon(pProcess); 
     Thread t = new Thread(proMon); 
     t.start(); 
     JFrame f = new JFrame(); //creates jframe f 

     if (isDebug.equals("Y")) { 
      System.out.println("Starting Thread"); 
     } 
     int imageNumber = 0; 

     while (!proMon.isComplete()) { 
      updateFrame(f, billBoardImageFileLocation, imageNumber); 
      Thread.sleep(Integer.parseInt(billBoardImageUpdateInterval)*1000); 
      if (isDebug.equals("Y")) { 
       System.out.println("Updating Framework"); 
      } 
      imageNumber++; 

     } 
     f.dispose(); 
    } 
} 

回答

1
JLabel lbl = new JLabel(image); 

不要创建一个新的标签,只是更新现有标签的图标:

label.setIcon(image); 

所以改变方法参数的标签,以及帧通过。

这就是所有你需要做的。

+0

非常感谢您的回答。它运作良好。 – Jaepyoung

1

您正在Swing事件线程上执行长时间运行的代码,将其冻结。解决方案:不要。使用Swing的计时器更换您的图片,因为这将允许不Swing事件线程上的步骤重复操作。也不要在这个线程上调用Thread.sleep。有关EDT的更多信息,Swing事件调度线程请阅读Concurrency in Swing