2017-01-30 201 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(); 
    } 
}