将图像绘制到JFrame中的JPanel

时间:2012-01-31 16:26:04

标签: java image swing jframe jpanel

我正在设计一个程序,在JFrame中包含两个JPanel,一个用于保存图像,另一个用于保存GUI组件(Searchfields等)。我想知道如何将图像绘制到JFrame中的第一个JPanel?

以下是我的构造函数中的示例代码:

public UITester() {
    this.setTitle("Airplane");
    Container container = getContentPane();
    container.setLayout(new FlowLayout());
    searchText = new JLabel("Enter Search Text Here");
    container.add(searchText);
    imagepanel = new JPanel(new FlowLayout());
    imagepanel.paintComponents(null);
   //other constructor code

}

public void paintComponent(Graphics g){
    super.paintComponents(g);
    g.drawImage(img[0], -50, 100, null);
}

我试图覆盖JPanel的paintComponent方法来绘制图像,但是当我尝试编写时,这会导致我的构造函数出现问题:

imagepanel.paintComponents(null);

因为它只允许我传递方法null,而不是Graphics g,任何人都知道修复此方法或我可以用来在JPanel中绘制图像的其他方法吗?感谢帮助! :)

一切顺利,并提前感谢! 马特

3 个答案:

答案 0 :(得分:14)

我想建议一种更简单的方法,

  image = ImageIO.read(new File(path));
  JLabel picLabel = new JLabel(new ImageIcon(image));

Yayy!现在你的形象是摆动组件!将它添加到框架或面板或您通常做的任何事情!可能也需要重新粉刷,比如

  jpanel.add(picLabel);
  jpanel.repaint(); 

答案 1 :(得分:7)

您可以使用JLabel.setIcon()在JPanel上放置图像here

另一方面,如果您想要一个带背景的面板,您可以查看this教程。

答案 2 :(得分:6)

无需从构造函数手动调用paintComponent()。问题是您为Graphics对象传递null。相反,覆盖paintComponent()并使用传入的Graphics对象进行绘制的方法。检查此tutorial。以下是JPanel带图片的示例:

class MyImagePanel extends JPanel{ 
    BufferedImage image;
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        if(image != null){
            g.drawImage(image, 0, 0, this);
        }
    }
}
相关问题