Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 564
MattTheHack Avatar asked Jan 31 '12 16:01

MattTheHack


People also ask

Can you add image to JPanel?

You need to add the MapLabel to the top JPanel, and make sure to size them all to the full size of the image (by overriding the GetPreferredSize()). Save this answer.

Can you draw on JFrame?

Drawing in the JFrameOnce we have a JFrame, we will get access to a graphics object on the frame. The graphics screen is set up as a grid of pixels where the upper left coordinate is 0,0. This is relative to where the canvas is on the viewframe.

Can a JPanel contain JFrame?

These classes are imported and then used in many GUI applications. We use the last, Graphics, to render visuals (e.g., figures, pictures, and even text) in a JPanel that contains the graphics part of a JFrame.


1 Answers

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);
        }
    }
}
like image 104
tenorsax Avatar answered Sep 16 '22 11:09

tenorsax