I'm wondering if there is any way to set a JPanel's background to an image instead of just a colour. Thanks and I'm working on dr. java
+2
A:
One option is to extend JPanel as they do here. There's another (simpler) example using the same basic technique on JavaRanch.
Bill the Lizard
2009-01-07 18:10:08
A:
You can subclass JPanel - here is an extract from my ImagePanel, which puts an image in any one of 5 locations, top/left, top/right, middle/middle, bottom/left or bottom/right:
public void setImage(Image img, int vs, int hs) {
mmImage=img;
mmVrtShift=vs;
mmHrzShift=hs;
mmSize=(img!=null ? new Dimension(img.getWidth(null),img.getHeight(null)) : null);
}
public void setTopLeftImage(Image img, int vs, int hs) {
tlImage=img;
tlVrtShift=vs;
tlHrzShift=hs;
tlSize=(img!=null ? new Dimension(img.getWidth(null),img.getHeight(null)) : null);
}
public void setTopRightImage(Image img, int vs, int hs) {
trImage=img;
trVrtShift=vs;
trHrzShift=hs;
trSize=(img!=null ? new Dimension(img.getWidth(null),img.getHeight(null)) : null);
}
public void setBottomLeftImage(Image img, int vs, int hs) {
blImage=img;
blVrtShift=vs;
blHrzShift=hs;
blSize=(img!=null ? new Dimension(img.getWidth(null),img.getHeight(null)) : null);
}
public void setBottomRightImage(Image img, int vs, int hs) {
brImage=img;
brVrtShift=vs;
brHrzShift=hs;
brSize=(img!=null ? new Dimension(img.getWidth(null),img.getHeight(null)) : null);
}
...
protected void paintComponent(Graphics gc) {
super.paintComponent(gc);
Dimension cs=getSize(); // component size
gc=gc.create();
gc.clipRect(insets.left,insets.top,(cs.width-insets.left-insets.right),(cs.height-insets.top-insets.bottom));
if(mmImage!=null) { gc.drawImage(mmImage,(((cs.width-mmSize.width)/2) +mmHrzShift),(((cs.height-mmSize.height)/2) +mmVrtShift),null); }
if(tlImage!=null) { gc.drawImage(tlImage,(insets.left +tlHrzShift),(insets.top +tlVrtShift),null); }
if(trImage!=null) { gc.drawImage(trImage,(cs.width-insets.right-trSize.width+trHrzShift),(insets.top +trVrtShift),null); }
if(blImage!=null) { gc.drawImage(blImage,(insets.left +blHrzShift),(cs.height-insets.bottom-blSize.height+blVrtShift),null); }
if(brImage!=null) { gc.drawImage(brImage,(cs.width-insets.right-brSize.width+brHrzShift),(cs.height-insets.bottom-brSize.height+brVrtShift),null); }
}
Software Monkey
2009-01-08 08:32:39