Drawing an Image to a JPanel within a JFrame

有些话、适合烂在心里 提交于 2019-11-27 02:49:19

问题


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

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

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


回答1:


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



回答2:


You can use the JLabel.setIcon() to place an image on the JPanel as shown here.

On the other hand, if you want to have a panel with a background, you can take a look at this tutorial.




回答3:


There is no need to manually invoke paintComponent() from a constructor. The problem is that you passing null for a Graphics object. Instead, override paintComponent() and you use the Graphics object passed in to the method you will be using for painting. Check this tutorial. Here is an example of JPanel with image:

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


来源:https://stackoverflow.com/questions/9083096/drawing-an-image-to-a-jpanel-within-a-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!