java - Background image for a jPanel not working -


i new making guis decided try the windows builder eclipse, , while great have doubts. have been searching cannot seen find way add background image "menu". example tried this:

public menu() {     setdefaultcloseoperation(jframe.exit_on_close);     setbounds(50, 50, 300, 250); //dimensiones  contentpane = new jpanel() {  //imagen de fondo      public void paintcomponent(graphics g) {             image img = toolkit.getdefaulttoolkit().getimage(             menu.class.getresource("/imgs/rotom.jpg"));             g.drawimage(img, 0, 0, this.getwidth(), this.getheight(), this);           }   };   

and adding following classes:

 import java.awt.graphics;    import java.awt.image;    import java.awt.toolkit;   

but no avail window remains dull grey color, far code standard 1 windowsbuilder cooks plus 4 buttons doubt they're of importance here. shouldn't code added override paintcomponent() method of jpanel , draw image in it?

the class menu in package within project , image within imgs package within same project well.

thanks lot in advance.

a simple method, if you're not interested in resizing background image or applying effects use jlabel...

bufferedimage bg = imageio.read(menu.class.getresource("/imgs/rotom.jpg")); jlabel label = new jlabel(new imageicon(bg)); setcontentpane(label); setlayout(...); 

there limitations approach (beyond scaling), in preferred size of label of image , never take account it's content. both , bad.

the other approach, seem using, use specialised component

public class backgroundpane extends jpanel {      private bufferedimage img;      public backgroundpane(bufferedimage img) {         this.img = img;     }      @override     public dimension getpreferredsize() {         return img == null ? super.getpreferredsize() : new dimension(img.getwidth(), img.getheight());     }      @override     protected void paintcomponent(graphics g) {         super.paintcomponent(g);         g.drawimage(img, 0, 0, this);     } } 

you should avoid trying perform task in paintcomponent method may take time complete paintcomponent may called , in quick succession....

getting image scale when component resized entire question of self, ideas, take at...

oh, and, should avoid extending directly top level containers, jframe, reduce reusability components , lock single container


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -