英文:
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 < 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);
}
}
答案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));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论