Search code examples
javaswingactionlistenerpaintcomponentgraphics2d

Zoom an Image after ActionListener


I try to create an Image View Program and have a problem in Java Image's zoom in and zoom out :D

I create a JPanel and using BufferedImage to display an image in my computer. After clicking a button, it should be zoom . But the problem in here that, I overload the method paintComponent() in the JPanel to display a image as I want. After searching in the Google, I think I should use Graphic2D to deal with this problem. Follow on this post, the line

Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, newImageWidth , newImageHeight , null);

should be put in the overloaded method paintComponent(). Howerver, in my case, I want to zoom the image after clicking a button, so, how can i access to the paintComponent() to do the zoom ??

public class MiddlePanel extends JPanel {
private BufferedImage img;
private JButton jbtZoom = new JButton("Zoom");

public MiddlePanel(int width){            

    img = ImageIO.read(new FileInputStream(new File("C:\\Picture\\pic1.jpg")));

    this.setPreferredSize(new Dimension(800,460));        
}

public void paintComponent(Graphics g) {
    g.drawImage(img......);
}

public void addComponentActionListener(){
    jbtZoom.addActionListener(new ActionListener{
        public void actionPerformed(){
            //What should I do in here to zoom the image....
        }
    });
}

Thank for your help!


Solution

  • You need to change your design like so:

    • Store in a variable your zoom state and then your overridden paintComponent method should look at that variable to decide if/how much to zoom.
    • Your ActionListener will update the variable then call repaint() on the panel.