在 JFrame 中将图像绘制到 JPanel

Drawing an Image to a JPanel within a JFrame(在 JFrame 中将图像绘制到 JPanel)

本文介绍了在 JFrame 中将图像绘制到 JPanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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). I am wondering how do I draw the Image to the first JPanel within the JFrame?

这是我的构造函数的示例代码:

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

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

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 :

imagepanel.paintComponents(null);

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

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? 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(); 

这篇关于在 JFrame 中将图像绘制到 JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 JFrame 中将图像绘制到 JPanel

基础教程推荐