Reputation: 39
Hello guys i am trying to display a picture from a URL on my JFrame, but its not working. Here is the code below: Note that MYJ is the name of my JLabel. I showed a tutorial here already but when I am trying to work with it, it displays on a separate label that was already created.
import java.awt.Image;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class MYPIX extends javax.swing.JFrame {
public void myFrame (){
}
/**
* Creates new form MYPIX
*/
public MYPIX() {
initComponents();
Image image = null;
try {
URL url = new URL("http://i.imgur.com/xiVXrCD.jpg");
image = ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
ImageIcon I22 = new ImageIcon();
MYJ.setIcon(I22);
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MYPIX().setVisible(true);
}
});
}
private javax.swing.JLabel MYJ;
// End of variables declaration
}
Upvotes: 2
Views: 5602
Reputation: 347334
Your exception block will only be called if something goes wrong, instead, within the try
block, you should be setting the lable's icon property after it's loaded successfully (because no error was raised during the read
process, the following lines in the try
block can be executed
URL url = new URL("http://i.imgur.com/xiVXrCD.jpg");
image = ImageIO.read(url);
MYJ.setIcon(new ImageIcon(image));
Don't forget to add the JLabel
to the frame.
You might also like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others
Upvotes: 8
Reputation: 6751
try {
BufferedImage img = ImageIO.read(new URL("http://1821662466.rsc.cdn77.org/images/google_apps_education.jpg"));
imgLabel.setIcon(new javax.swing.ImageIcon(img));
}
catch(IOException ex) {
}
You can try this method
Upvotes: 0
Reputation: 528
Here is the updated code that is working:
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class MYPIX extends javax.swing.JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public void myFrame (){
}
/**
* Creates new form MYPIX
*/
public MYPIX() {
// initComponents();
try {
this.setSize(200, 200);
URL url = new URL("http://i.imgur.com/xiVXrCD.jpg");
BufferedImage image = ImageIO.read(url);
MYJ = new JLabel(new ImageIcon(image));
image = ImageIO.read(url);
this.add(MYJ);
} catch (IOException e) {
e.printStackTrace();
ImageIcon I22 = new ImageIcon();
MYJ.setIcon(I22);
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MYPIX().setVisible(true);
}
});
}
private javax.swing.JLabel MYJ;
// End of variables declaration
}
Upvotes: 0