简体   繁体   English

在 JFrame 中将图像绘制到 JPanel

[英]Drawing an Image to a JPanel within a JFrame

I am designing a program that contains two JPanels within a JFrame, one is for holding an image, the other for holding GUI components(Searchfields etc).我正在设计一个在 JFrame 中包含两个 JPanel 的程序,一个用于保存图像,另一个用于保存 GUI 组件(搜索字段等)。 I am wondering how do I draw the Image to the first JPanel within the JFrame?我想知道如何将图像绘制到 JFrame 中的第一个 JPanel?

Here is a sample code from my constructor :这是我的构造函数中的示例代码:

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);
}

I was trying to override the paintComponent method of JPanel to paint the image, but this causes a problem in my constructor when I try to write :我试图覆盖 JPanel 的 paintComponent 方法来绘制图像,但是当我尝试编写时,这会导致我的构造函数出现问题:

imagepanel.paintComponents(null);

As it will only allow me to pass the method null, and not Graphics g, anybody know of a fix to this method or another method i can use to draw the image in the JPanel?因为它只允许我传递方法 null,而不是 Graphics g,有人知道此方法的修复程序或我可以用来在 JPanel 中绘制图像的另一种方法吗? Help is appreciated!帮助表示赞赏! :) :)

All the best and thanks in advance!祝一切顺利,提前致谢! Matt马特

I'd like to suggest a more simple way,我想建议一个更简单的方法,

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

Yayy!耶! Now your image is a swing component !现在您的图像是一个摆动组件! add it to a frame or panel or anything like you usually do!将它添加到框架或面板或您通常做的任何事情! Probably need a repainting too , like可能也需要重新粉刷,比如

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

You can use the JLabel.setIcon() to place an image on the JPanel as shown here .您可以使用JLabel.setIcon()放置在图像上的JPanel如图所示这里

On the other hand, if you want to have a panel with a background, you can take a look at this tutorial.另一方面,如果你想要一个带背景的面板,你可以看看这个教程。

There is no need to manually invoke paintComponent() from a constructor.无需从构造函数手动调用paintComponent() The problem is that you passing null for a Graphics object.问题是您为Graphics对象传递了 null 。 Instead, override paintComponent() and you use the Graphics object passed in to the method you will be using for painting.相反,覆盖paintComponent()并使用传递给将用于绘画的方法的Graphics对象。 Check this tutorial .检查本教程 Here is an example of JPanel with image:这是带有图像的JPanel示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM