2017-01-30 116 views
0

我想要一個簡單的JFrameJLabel(顯示圖像作爲圖標)和JSlider(切換40個圖像)。預加載圖像用作JLabel圖標

當我在滑塊的StateChange事件上加載新圖像時,程序變得非常慢,特別是當我滑動快時。

所以我正在考慮預載40個圖像,並通過滑塊替換它們。這是否智能和可能?

+2

是的,它是可能的。在這個階段,我們無法幫助您解決具體問題,因爲您沒有提供任何信息。爲什麼不簡單地先嚐試一下呢?如果你不知道,我們怎麼知道你可能會遇到什麼問題? –

+0

查看'java.awt.MediaTracker'類和'ImageIcon'也使用'MediaTracker',如果我沒有錯 - 所以預加載圖像非常簡單 –

+1

不要直接在事件監聽器中加載圖標。改爲使用'javax.swing.Timer'。因此,您可以避免在用戶快速滑動時簡單加載不需要的圖像(只需取消舊計時器並開始新計時器)。 –

回答

2

我認爲,你有這樣的事情:

public class MyClass { 
    // other declarations 
    private JLabel label; 
    // other methods 
    public void stateChange(ChangeEvent e) { 
     label.setIcon(new ImageIcon(...)); // here is code to determine name of the icon to load. 
       timer = null; 
    } 
} 

你需要的是改變你的代碼如下:

public class MyClass { 
    // other declarations 
    private JLabel label; 
    private Timer timer; // javax.swing.Timer 
    // other methods 
    public void stateChange(ChangeEvent e) { 
     if (timer != null) { 
      timer.stop(); 
     } 
     timer = new Timer(250, new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       label.setIcon(new ImageIcon(...)); // here is code to determine name of the icon to load. 
       timer = null; 
      } 
     }); 
     timer.setRepeats(false); 
     timer.start(); 
    } 
}