JPanel with image background

How to place image wallpaper 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? 
+7
java background-image jpanel
source share
2 answers
+2
source share

Perhaps the easiest way is to load Image into ImageIcon and display it in JLabel , however:
To directly "draw" an image on JPanel, redefine the JPanel paintComponent(Graphics) method like this:

 public void paintComponent(Graphics page) { super.paintComponent(page); page.drawImage(img, 0, 0, null); } 

where img is Image (possibly loaded via an ImageIO.read() call).

Graphics#drawImage is a very overloaded command that will allow you to be very specific as to how and where you draw the image for the component.

You can also get โ€œfantasyโ€ and scale the image to your pleasure using the Image#getScaledInstance . It takes -1 for the width or height parameter to keep the aspect ratio of the image the same.

Putting it in a more bizarre 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 ); } 
+4
source share

All Articles