javabufferedimage

Why is my newly generated BufferedImage not drawn on my JPanel?


I am trying to display a newly generated BufferedImage on a JPanel but its not showing. Other components like Buttons or Rectangles can be displayed without problems, and I can't figure it out.

This is my code:

public class panelsa extends JPanel{
    BufferedImage img;
    
    public panelsa(){
        setPreferredSize(new Dimension(400,400));
        initImg();
    }

    private void initImg()
    {
        Random rnd = new Random();
        img = new BufferedImage(400, 400, BufferedImage.TYPE_INT_ARGB);
        for (int i = 0; i < img.getHeight(); i++){
            for (int j = 0; j < img.getWidth(); j++){
                img.setRGB(i, j, rnd.nextInt(16777216));
            }
        }       
    }

    @Override
    protected void paintComponent(Graphics aG){
        super.paintComponent(aG);
        aG.drawImage(img, 0, 0, null);
    }
}

Solution

  • BufferedImage.setRGB actually works with ARGB, so there might be unintentional transparency, so do

    img.setRGB(i, j, 0xFF000000 | rnd.nextInt(16777216));