java - ImageIcon is displayed as a small square -


where problem. not show image properly.

default.png = a busy cat*********

what see = a busy cat*********

i dont think there problem png. in src , refreshed on eclipse.

codes:

import java.awt.*;  import javax.swing.*;  public class main {  public static void main(string[] args) {       jframe jf = new jframe();      jf.settitle( "test");     jf.setlayout( new flowlayout());     jf.setsize(350, 450);     jf.setvisible(true);     jf.setdefaultcloseoperation(jframe.exit_on_close);       jf.add(new panel());  }  } 

panel:

import java.awt.graphics; import javax.swing.imageicon; import javax.swing.jpanel;   public class panel extends jpanel {  // properties  public imageicon icon;  // constructors  public panel() {      icon = new imageicon(this.getclass().getresource("default.png")); }  public void paintcomponent(graphics g) {     super.paintcomponent(g);     g.drawimage(icon.getimage(), 0, 0, null);  }   } 

this answer addresses criticism of answer op. example incorporates advice added in various comments.

enter image description here

import java.awt.*; import java.awt.image.bufferedimage; import javax.swing.*;  import java.net.url; import javax.imageio.imageio; import javax.swing.border.lineborder;  public class main {      public static void main(string[] args) throws exception {         url url = new url("http://i.imgur.com/o0e0agd.png");         bufferedimage bi = imageio.read(url);         jframe jf = new jframe();          jf.settitle("test");         jf.setlayout(new flowlayout());         //jf.setsize(350, 450); pack()         jf.setdefaultcloseoperation(jframe.exit_on_close);          jf.add(new backgroundimagepanel(bi));          jf.pack();         jf.setminimumsize(jf.getsize());         jf.setvisible(true);     } }  class backgroundimagepanel extends jpanel {      public image img;      // constructor     public backgroundimagepanel(image img) {         this.img = img;         this.setborder(new lineborder(color.red, 2));     }      public void paintcomponent(graphics g) {         super.paintcomponent(g);         g.drawimage(img, 0, 0, this);         // g.drawimage(img, 0, 0, getwidth(), getheight(), this);  // better!     }      @override     public dimension getpreferredsize() {         dimension d = super.getpreferredsize();         int w = d.width>img.getwidth(this) ? d.width : img.getwidth(this);         int h = d.height>img.getheight(this) ? d.height : img.getheight(this);          return new dimension(w, h);     } } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

node.js - Using Node without global install -

php - CakePHP HttpSockets send array of paramms -