【发布时间】:2010-09-23 04:00:46
【问题描述】:
Image image = GenerateImage.toImage(true); //this generates an image file
JLabel thumb = new JLabel();
thumb.setIcon(image)
【问题讨论】:
Image image = GenerateImage.toImage(true); //this generates an image file
JLabel thumb = new JLabel();
thumb.setIcon(image)
【问题讨论】:
您必须向 JLabel 提供 Icon 实现(即 ImageIcon)。您可以通过setIcon 方法(如您的问题)或通过JLabel 构造函数来完成:
Image image=GenerateImage.toImage(true); //this generates an image file
ImageIcon icon = new ImageIcon(image);
JLabel thumb = new JLabel();
thumb.setIcon(icon);
我建议您阅读 JLabel、Icon 和 ImageIcon 的 Javadoc。另外,您可以查看How to Use Labels Tutorial,了解更多信息。
【讨论】:
要从 URL 中获取图像,我们可以使用以下代码:
ImageIcon imgThisImg = new ImageIcon(PicURL));
jLabel2.setIcon(imgThisImg);
它完全适合我。 PicUrl 是一个字符串变量,用于存储图片的 url。
【讨论】:
(如果您使用的是 NetBeans IDE) 只需在您的项目中创建一个文件夹,但在 src 文件夹之外。将文件夹命名为 Images。然后把图片放到Images文件夹下,在下面写代码。
// Import ImageIcon
ImageIcon iconLogo = new ImageIcon("Images/YourCompanyLogo.png");
// In init() method write this code
jLabelYourCompanyLogo.setIcon(iconLogo);
现在运行你的程序。
【讨论】:
最短的代码是:
JLabel jLabelObject = new JLabel();
jLabelObject.setIcon(new ImageIcon(stringPictureURL));
stringPictureURL 是图片的PATH。
【讨论】:
您可以在 main(String[] args) 函数中编写的简单代码
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//application will be closed when you close frame
frame.setSize(800,600);
frame.setLocation(200,200);
JFileChooser fc = new JFileChooser();
if(fc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION){
BufferedImage img = ImageIO.read(fc.getSelectedFile());//it must be an image file, otherwise you'll get an exception
JLabel label = new JLabel();
label.setIcon(new ImageIcon(img));
frame.getContentPane().add(label);
}
frame.setVisible(true);//showing up the frame
【讨论】: