Isuru Pathirana
Isuru Pathirana

Reputation: 1118

Resize and Redraw a image in a JPanel

I'm creating a simple java program to load a image and zoom in/out the image. So far I have been able load the picture and zoom it. But when drawing the zoomed out image I can still see the previous image on the JPanel.

Code for loading the image

JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Images(jpg,png,gif)", "jpg","png","gif"));
int opt = fileChooser.showOpenDialog(this);
if(opt  == JFileChooser.APPROVE_OPTION){
    String filePath = fileChooser.getSelectedFile().getAbsolutePath();
    try {
        bufImage = ImageIO.read(fileChooser.getSelectedFile());
    } catch (IOException ex) {
        Logger.getLogger(ImageZoom.class.getName()).log(Level.SEVERE, null, ex);
    }
    image = new ImageIcon(filePath);
    imgWidth = image.getIconWidth();
    imgHeight = image.getIconHeight();

    imagePanel.getGraphics().drawImage(image.getImage(), 0, 100, image.getIconWidth(), image.getIconHeight(), imagePanel);
}

Code for zooming in

double scale_factor = 1.5;
imagePanel.getGraphics().drawImage(image.getImage(), 0, 100, (int)(imgWidth*=scale_factor), (int)(imgHeight*=scale_factor), imagePanel);

Code for zooming out

double scale_factor = 0.5;
imagePanel.getGraphics().drawImage(image.getImage(), 0, 100, (int)(imgWidth*=scale_factor), (int)(imgHeight*=scale_factor), imagePanel);  

Can some one please suggest a way to only have the resized image on the panel?
This is how zooming out looks like. same problem occurs when opening a new picture.
I tried repainting the panel but then everything vanishes.

This is how zooming out looks like

Upvotes: 0

Views: 980

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347332

That's because imagePanel.getGraphics() isn't how custom painting works in Swing. Instead, create a custom class which extends from something like JPanel and override it's paintComponent method, painting your scaled image there (making sure to call super.paintComponent first)

See Painting in AWT and Swing and Performing Custom Painting for more details

For example:

Upvotes: 2

Related Questions