Java 在JFrame中向JPanel绘制图像

Java 在JFrame中向JPanel绘制图像,java,image,swing,jframe,jpanel,Java,Image,Swing,Jframe,Jpanel,我正在设计一个程序,在JFrame中包含两个JPanel,一个用于保存图像,另一个用于保存GUI组件(搜索字段等)。我想知道如何将图像绘制到JFrame中的第一个JPanel 以下是我的构造函数中的示例代码: public UITester() { this.setTitle("Airplane"); Container container = getContentPane(); container.setLayout(new FlowLayout()); sea

我正在设计一个程序,在JFrame中包含两个JPanel,一个用于保存图像,另一个用于保存GUI组件(搜索字段等)。我想知道如何将图像绘制到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
}

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

imagepanel.paintComponents(null);
因为它只允许我传递方法null,而不允许传递图形g,有人知道这个方法的修复方法或者我可以使用的另一个方法来在JPanel中绘制图像吗?谢谢你的帮助!:)

祝您万事如意,提前感谢! Matt

您可以使用在JPanel上放置图像,如图所示


另一方面,如果你想要一个有背景的面板,你可以看看教程。

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

  image = ImageIO.read(new File(path));
  JLabel picLabel = new JLabel(new ImageIcon(image));
耶!现在,您的图像是一个swing组件!将其添加到框架、面板或任何类似于您通常所做的操作中!可能也需要重新粉刷,比如

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

无需从构造函数手动调用
paintComponent()
。问题是为
图形
对象传递null。相反,重写
paintComponent()
,然后使用传递给将用于绘制的方法的
Graphics
对象。看看这个。以下是带有图像的
JPanel
示例:

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

从构造器中调用paintComponents的想法是什么?。简单地删除它。顺便说一句,你为什么不画图像最左边的50个像素呢?最好链接到最新版本的JavaDocs。我已将您的答案编辑为指向J2SE 7。有关获取最新文档链接的提示,请参阅。@AndrewThompson:对不起,J2SE现在不是被称为JavaSE吗。Regards@GagandeepBali什么,这一分钟?Sun过去经常更换事物的名称,以至于我厌倦了跟上最新的流行语(@AndrewThompson:呵呵,太对了,只是有人编辑过我的答案,这就是为什么我至今还记得它,否则毫无疑问这些东西很难记住。关于一个小提示。考虑到这听起来很像一个应用程序资源,它通常是通过URL而不是文件访问的。如果我想在particu上画图怎么办lar x和y位置
class MyImagePanel extends JPanel{ 
    BufferedImage image;
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        if(image != null){
            g.drawImage(image, 0, 0, this);
        }
    }
}