Reputation:
I want to have a simple JFrame
with a JLabel
(to show images as an icon) and a JSlider
(to switch between 40 images).
When I load the new images on a StateChange
event of the slider, the program gets very slow, especially when I slide fast.
So I was thinking of preloading the 40 images and replacing them via the slider. Is this smart and possible?
Upvotes: 0
Views: 194
Reputation: 11327
I assume, you have something like this:
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;
}
}
What you need is to change your code as following:
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();
}
}
Upvotes: 2