javaswing图片读取
时间: 2023-09-12 12:03:08 浏览: 85
Java Swing 可以通过 `JLabel` 控件来显示图片。以下是一个简单的例子,演示如何从文件中读取图片并在 `JLabel` 控件中显示它:
```java
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ImageDisplayExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
JLabel label = new JLabel();
// 从文件中读取图片
ImageIcon icon = new ImageIcon("image.jpg");
Image image = icon.getImage();
// 将图片设置为 JLabel 的图标
label.setIcon(icon);
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
}
}
```
在这个例子中,我们首先创建了一个 `JFrame` 对象和一个 `JLabel` 对象。然后,我们使用 `ImageIcon` 类从文件中读取图片,并将其设置为 `JLabel` 的图标。最后,我们将 `JLabel` 添加到 `JFrame` 中,并显示 `JFrame`。
请注意,当使用 `ImageIcon` 从文件中读取图片时,文件路径应该是相对于 Java 程序的工作目录的路径。