• Post Reply Bookmark Topic Watch Topic
  • New Topic

How do I draw .JPG Image to JPanel?

 
Will Blanc
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know I can draw an .JPG image to my GUI JPanel, but can I take an image directly from the internet? Here's what I mean:

class MyPanel extends JPanel {

public void paintComponent(Graphics g) {
Image image = new ImageIcon("http://dwarfstar.brainiac.com/barbarianprince/barbarianprince_map1.jpg").getImage(); //This is the line in question. It does not draw
g.drawImage(image, 0, 0, this);
}
}

Thanks!
 
Gregg Bolinger
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at the API for ImageIcon and you tell me which constructor might handle grabbing an image from a URL. ;)
 
Rob Camick
Ranch Hand
Posts: 2699
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should never do I/O in the paintComponent() method. This method gets call any time the component needs to be repainted so you don't want to reread the image.
 
Rob Spoor
Sheriff
Posts: 20816
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Agreed. Instead, make the Image a private field that you initialize once in the constructor.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!