How to change image with the click of a button in java

sabbibJAVA picture sabbibJAVA · Aug 23, 2012 · Viewed 8.7k times · Source

If already an image is display, by clicking a button how can i change it to another one?

Say I have two image buffered.

bi = ImageIO.read(new File("1.jpg");
bi2 = ImageIO.read(new File("2.jpg"));

and to display the bi I am using

public void paint(Graphics g){
    super.paintComponent(g);

    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); 
    int w = ((int) dim.getWidth() / 2) - (bi.getWidth() / 2);
    int h = ((int) dim.getHeight() / 2) - (bi.getHeight() / 2);

    g.drawImage(bi, w, h, null);
}

I am tried to do this.

JButton b = new JButton("Change Image");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae){
        bi = bi2;
        paint(null);
    }
});

this set bi to a new image and paint() method called, but the image viewer itself doesnt appear at all now.

continuation of how to set JFrame background transparent but JPanel or JLabel Background opaque?

Answer

MadProgrammer picture MadProgrammer · Aug 23, 2012

You need to request a repaint.

JButton b = new JButton("Change Image");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae){
        bi = bi2;
        //invalidate();
        repaint();
    }
});

It may also be necessary to call invalidate first to allow the container to be marked for repainting by the repaint manager

If you know the area to be painted (ie the old area and the new area) you could call paintImmediately instead

So something like this could also work...

int w = ((int) dim.getWidth() / 2) - (bi.getWidth() / 2);
int h = ((int) dim.getHeight() / 2) - (bi.getHeight() / 2);
Rectangle oldArea = new Rectangle(w, h, bi.getWidth(), bi.getHeight());

bi = bi2;
w = ((int) dim.getWidth() / 2) - (bi.getWidth() / 2);
h = ((int) dim.getHeight() / 2) - (bi.getHeight() / 2);
Rectangle newArea = new Rectangle(w, h, bi.getWidth(), bi.getHeight());

Area area = new Area();
area.add(oldArea);
area.add(newArea);

Rectangle updateArea = area.getBounds();
paintImmediately(updateArea);