Java/JAVA-swing

Advertisement


Question
hello sir,
Can you please tell me how to set background image on JFrame , and another short image over this background image.i want to draw these images on JPanel, and some other swing component oner these images.
But The images are available at another website, so we have to access thes images thru URL.
so please reply me with a short example with only how to set images through URL on JPanel

Answer
If you are using an applet, you will not be able to access URLs outside where the applet lives unless
1. your applet is signed
OR
2. the website has a crossdomain.xml file in the root directory that looks like (e.g. Flickr has this):

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
 <allow-access-from domain="*" />
</cross-domain-policy>

If you are making a Java desktop application, this is not an issue.

For JFrame, you can use your own content pane to draw images too. To set the content pane of the JFrame use:

JPanel backgroundImage = ...;
frame.setContentPane(backgroundImage);


If you want to display an image in the background of a JPanel you will need to extend it and draw the image yourself. Like:

public class BackgroundImagePanel extends JPanel
{
  private Image image;
  public BackgroundImagePanel(URL url) throws IOException
  {
     image = ImageIO.read(url);
  }
  @Override
  protected void paintComponent(Graphics g)
  {
     g.drawImage(image, 0, 0, this);
  }
}


If you don't want the program to wait before the image fully loads to display stuff (like a web page) then you will want to use
image = getToolkit().createImage(url);

Any components you add to a BackgroundImagePanel will draw on top of the image.

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Artemus Harper

Expertise

I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.

Experience

I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Organizations
Washington State University

Education/Credentials
MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2016 About.com. All rights reserved.