首页 文章

将图像绘制到JFrame中的JPanel

提问于
浏览
9

我正在设计一个程序,在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 回答

  • 6

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

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

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

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

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

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

  • 14

    无需从构造函数手动调用 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);
            }
        }
    }
    

相关问题