2015-10-02 49 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