为什么我的新生成的BufferedImage没有绘制在我的JPanel上?

huangapple go评论70阅读模式
英文:

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

问题

我正在尝试在JPanel上显示一个新生成的BufferedImage,但它没有显示出来。其他组件如按钮或矩形可以正常显示,我想不出原因。

这是我的代码:

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);
	}
}
英文:

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 &lt; img.getHeight(); i++){
			for (int j = 0; j &lt; 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);
	}
}

答案1

得分: 0

BufferedImage.setRGB实际上使用ARGB,因此可能会有意外的透明度,所以可以这样做:

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

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

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

huangapple
  • 本文由 发表于 2023年7月11日 03:37:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76656811.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定