大家好,我正试图在我的JFrame上显示来自URL的图片,但它不起作用。下面是代码:请注意,MYJ是名称我的JLabel。我已经在这里展示了一个教程,但当我尝试使用它时,它会显示在已经创建的单独标签上。
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
}
只有在出现问题时才会调用您的异常块,相反,在try
块中,您应该在标签成功加载后设置标签的图标属性(因为在read
过程中没有引发错误,所以try
块中的以下行可以执行
URL url = new URL("http://i.imgur.com/xiVXrCD.jpg");
image = ImageIO.read(url);
MYJ.setIcon(new ImageIcon(image));
不要忘记将JLabel
添加到帧中。
您可能还想了解Java TM编程语言的代码约定,这将使人们更容易阅读您的代码,也使您更容易阅读其他
以下是正在运行的更新代码:
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
}
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) {
}
您可以尝试这种方法