Java. How can you set the background of a panel with an image?

I am wondering if there is a way to set JPanel background for image instead of color. Thanks and I am working on a doctor. Java

+1


source to share


2 answers


One option is to extend the JPanel as they are here . There's another (simpler) example out there using the same basic technique on JavaRanch .



+2


source


You can subclass the JPanel - here is an excerpt from my ImagePanel that puts the image in any 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); }
    }

      

0


source







All Articles