java swing ImageIcon
时间: 2023-10-06 14:07:00 浏览: 62
Java Swing 中的 ImageIcon 类是一个用于显示图像的组件。它可以从文件、URL、字节数组或 Image 对象中加载图像,并将其显示在 Swing 容器中。
下面是一个简单的例子,演示如何使用 ImageIcon 在 JFrame 中显示一张图片:
```java
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ImageIconExample {
public static void main(String[] args) {
// 创建 JFrame 对象
JFrame frame = new JFrame("ImageIcon Example");
// 创建 ImageIcon 对象
ImageIcon icon = new ImageIcon("path/to/image.jpg");
// 创建 JLabel 对象,用于显示图像
JLabel label = new JLabel(icon);
// 将 JLabel 添加到 JFrame 中
frame.getContentPane().add(label);
// 设置 JFrame 大小和可见性
frame.setSize(400, 300);
frame.setVisible(true);
}
}
```
在这个例子中,我们首先创建了一个 JFrame 对象,然后创建了一个 ImageIcon 对象,接着创建了一个 JLabel 对象,并将 ImageIcon 对象设置为 JLabel 的图像。最后将 JLabel 添加到 JFrame 中,设置 JFrame 的大小和可见性。
当运行这个程序时,将会在 JFrame 中显示指定路径下的图片。如果需要加载其他来源的图像,可以使用 ImageIcon 的其他构造函数来实现。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)