How to put image background on JPANEL?
JPanel pDraw = new JPanel(new GridLayout(ROWS,COLS,2,2));
pDraw.setPreferredSize(new Dimension(600,600)); //size of the JPanel
pDraw.setBackground(Color.RED); //How can I change the background from red color to image?
It is probably easiest to load the Image
into an ImageIcon
and display it in a JLabel
, however:
To directly 'draw' the image to the JPanel, override the JPanel's paintComponent(Graphics)
method to something like the following:
public void paintComponent(Graphics page)
{
super.paintComponent(page);
page.drawImage(img, 0, 0, null);
}
where img
is an Image
(possibly loaded through the ImageIO.read()
call).
Graphics#drawImage
is a heavily overloaded command which will allow you to be highly specific in how, how much, and where you paint the image to the component.
You can also get 'fancy' and scale the image to your pleasing using the Image#getScaledInstance
method. This will take a -1
for either the width
or the height
parameter in order to keep the aspect ratio of the image the same.
Putting it in a more fancy way:
public void paintComponent(Graphics page)
{
super.paintComponent(page);
int h = img.getHeight(null);
int w = img.getWidth(null);
// Scale Horizontally:
if ( w > this.getWidth() )
{
img = img.getScaledInstance( getWidth(), -1, Image.SCALE_DEFAULT );
h = img.getHeight(null);
}
// Scale Vertically:
if ( h > this.getHeight() )
{
img = img.getScaledInstance( -1, getHeight(), Image.SCALE_DEFAULT );
}
// Center Images
int x = (getWidth() - img.getWidth(null)) / 2;
int y = (getHeight() - img.getHeight(null)) / 2;
// Draw it
page.drawImage( img, x, y, null );
}
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