简体   繁体   中英

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.

这就是缩小的样子

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM