大家好我想在我的JFrame上显示网址中的图片, 但它不起作用。以下是代码:注意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
}
答案 0 :(得分:5)
你的异常块只有在出现问题时才会出现,而是在try
块内,你应该在成功加载后设置标签的图标属性(因为在read
期间没有出现错误进程,try
块中的以下行可以执行
URL url = new URL("http://i.imgur.com/xiVXrCD.jpg");
image = ImageIO.read(url);
MYJ.setIcon(new ImageIcon(image));
不要忘记将JLabel
添加到框架中。
您可能还希望阅读Code Conventions for the Java TM Programming Language,这样可以让人们更轻松地阅读您的代码并让您阅读其他代码
答案 1 :(得分:0)
以下是正在运行的更新代码:
private void extractFolder(String zipFile, String extractFolder)
{
try
{
int BUFFER = 2048;
File file = new File(zipFile);
ZipFile zip = new ZipFile(file);
String newPath = extractFolder;
new File(newPath).mkdir();
Enumeration zipFiles = zip.entries();
while (zipFiles.hasMoreElements())
{
ZipEntry entry = (ZipEntry) zipFiles.nextElement();
String currentEntry = entry.getName();
File destFile = new File(newPath, currentEntry);
// destFile = new File(newPath, destFile.getName());
File destinationParent = destFile.getParentFile();
// create the parent directory structure if needed
destinationParent.mkdirs();
if (!entry.isDirectory())
{
BufferedInputStream inputSteam = new BufferedInputStream(zip.getInputStream(entry));
int currentByte;
// init buffer
byte data[] = new byte[BUFFER];
FileOutputStream outStream = new FileOutputStream(destFile);
BufferedOutputStream bufferedOutSteam = new BufferedOutputStream(outStream, BUFFER);
while ((currentByte = inputSteam.read(data, 0, BUFFER)) != -1)
{
bufferedOutSteam.write(data, 0, currentByte);
}
bufferedOutSteam.flush();
outStream.flush();
bufferedOutSteam.close();
inputSteam.close();
outStream.close();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
答案 2 :(得分:0)
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) {
}
你可以试试这个方法