I have a JPanel which in turn has a JLabel with an icon. I'm using this JLabel as a background image. I want to be able to zoom in this image with the help of JSlider while using the netbeans GUI Builder but I can't seem to workout the stateChangedListener. Any help would be appreciated. Here's what I've got so far: 1- This is how I set the Image
public static void setImage(JLabel label,String path) {
ImageIcon myImage=new ImageIcon(path);
Image img=myImage.getImage();
Image newImg=img.getScaledInstance(label.getWidth(), label.getHeight(),Image.SCALE_SMOOTH);
ImageIcon image=new ImageIcon(newImg);
label.setIcon(image);
}
This is my stateChangedListener, it scales the image with +10 to the JLabel's height and width but the problem is that it will have to add a new image each time the slider is adjusted.
private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {
int value = jSlider1.getValue();
if(value==55){
String path=System.getProperty("user.dir")+File.separator+"sources"+File.separator+"1891.jpg";
ImageIcon myImage=new ImageIcon(path);
Image img=myImage.getImage();
Image newImg=img.getScaledInstance(label.getWidth()+10, label.getHeight()+10,Image.SCALE_SMOOTH);
ImageIcon image=new ImageIcon(newImg);
label.setIcon(image);
}
}
Try getting the image from the label's icon and then enlarge it:
private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {
int value = jSlider1.getValue();
if(value==55) {
ImageIcon myImage = (ImageIcon) label.getIcon();
Image img = myImage.getImage();
Image newImg = img.getScaledInstance(label.getWidth()+10, label.getHeight()+10,Image.SCALE_SMOOTH);
label.setIcon( new ImageIcon(newImg) );
}
}
This way you'll avoid creating a new image from the image file, however you'll still have to obtain a new image scaled instance with getScaledInstance
.
Hope this helps