0

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!

Community
  • 1
  • 1
Lup
  • 197
  • 1
  • 1
  • 7
  • `public void paintComponent(Graphics g) { g.drawImage(img......);` should be `public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(img......);` – Andrew Thompson Oct 18 '13 at 18:04
  • @AndrewThompson or simply override `public void paint(Graphics g)` instead of `public void paintComponent(Graphics g)` – vallentin Oct 20 '13 at 17:47
  • @Vallentin No! That is the wrong way to do custom painting in a `JComponent`. – Andrew Thompson Oct 20 '13 at 22:32

1 Answers1

3

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.
jzd
  • 23,473
  • 9
  • 54
  • 76