How to change image with one click in java

If the image is already displayed by clicking the button, how can I change it to another?

Say I have two buffered images.

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

and to display the bi that I use

 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 trying to do this.

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

this bi set is for the new image and paint () method, but the image viewer itself is not displayed at all.

continued how to set a transparent JFrame background, but JPanel or JLabel Background opaque?

-one
source share
1 answer

You need to request repaint .

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

You might also need to call invalidate first so that the container is marked for repainting by the repaint manager

If you know the area you want to paint (i.e. the old area and the new area), you can call paintImmediately instead

So something like this might work too ...

 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); 
+3
source

All Articles