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 ); }
Reese moore
source share