How can I add an image to a JPanel background. The image will not be scaled or resized. Thanks.
Asked
Active
Viewed 1.6k times
2
-
2duplicate http://stackoverflow.com/questions/299495/java-swing-how-to-add-an-image-to-a-jpanel – Preston Aug 27 '11 at 22:01
-
1and JPanel can be resized or not ..., for GUI related question your tag would be Swing + JPanel + Icon/Image/ImageIcon, look like as again empty question without reading tutorial, please post here code that shows your issue with Image/ImageIcon placed into JPanel that shouldn't be resiziable – mKorbel Aug 27 '11 at 22:24
-
@Preston Thanks. The example in the link answered the question. – FadelMS Aug 27 '11 at 22:46
2 Answers
2
/**
* @author
*
*/
public class ImagePanel extends JPanel {
private Image image = null;
public ImagePanel(String filename) {
this.image = new ImageIcon(filename).getImage();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, image.getWidth(null), image.getHeight(null), null);
}
/**
* @param args
*/
public static void main(String[] args) {
ImagePanel panel = new ImagePanel("resources/image.jpg");
JFrame frame = new JFrame("Frame");
frame.setSize(800, 600);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.setVisible(true);
}
}

Ammar
- 2,387
- 1
- 14
- 12
-
1Won't this scale with resize? See also [Initial Threads](http://download.oracle.com/javase/tutorial/uiswing/concurrency/initial.html). – trashgod Aug 28 '11 at 00:53
-
Perfect, if only more people would be this short with there answers! – basickarl Mar 13 '13 at 18:23
-1
You can override one of these methods:
JComponent.paint(Graphics g)
JComponent.paintComponent(Graphics g)

Ammar
- 2,387
- 1
- 14
- 12
-
3please remove `JComponent.paint(Graphics g)`, that really wrong method for painting in Java6' Swing – mKorbel Aug 27 '11 at 22:36