2

当我试图在 上显示图像时JFrame,它没有被加载。我displayImage(File file)在扩展类的类中定义了方法JFrame-

public void displayImage(File file)
{ 
        BufferedImage loadImg = StegImage.loadImage(file); 
        System.out.println(loadImg.getWidth() + "x" + loadImg.getHeight() + " image is loaded.");
        setVisible(true);
        setState(JFrame.NORMAL);
        setBounds(0, 0, loadImg.getWidth(), loadImg.getHeight()); 
        Graphics2D g = (Graphics2D)getRootPane().getGraphics();
        System.out.println("Drawing the image.");
        g.drawImage(loadImg, null, 0, 0);  
}

我在终端上得到的输出是 -

877 x 587 image is loaded.
Drawing the image.

但在框架中它是不可见的。

4

2 回答 2

3

不应像您那样绘制或调用组件的图形。如果您需要自定义图形渲染,请使用JComponentJPanel具有该paintComponent功能。覆盖它以在其中绘制。

class MyCanvas extends JComponent
{
  public BufferedImage bgImg; // your background image

  @Override
  public void paintComponent(Graphics g)
  {
     super.paintComponent(g);
     g.drawImage(bgImg, x, y, this); // draw background image
  } 
  }
}

读取您的图像并将其分配bgImgMyCanvas. 对于您的用例,您希望将图像用作 JFrame 的背景:将 MyCanvasas content 窗格的实例添加到JFrame.

 jFrame.setContentPane(new MyCanvas()); 
   // you might want to set layout or other thing to the
  // MyCanvas component before adding it

阅读一些在线教程,例如自定义图形绘制和在组件上绘制

于 2013-10-19T23:07:38.373 回答
1

1st创建一个公共的BufferedImage loadImg;变量在你的类之上,稍后在你的 displayImage(File file) 函数中初始化它;

   loadImg = StegImage.loadImage(file);

2nd创建一个绘制图像的函数;

public void paintComponent(Graphics g) {
    super.paintComponent(g);  // Paint background

    // Draw image at its natural size first.
    g.drawImage(loadImag, 0, 0, this); //85x62 image

    // Now draw the image scaled.
    g.drawImage(loadImag, 90, 0, 300, 62, this);
} 
于 2013-10-19T22:44:47.880 回答