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
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.
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.
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.
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With