我想将图像添加到框架中,但我不明白应该将图像文件保存在哪里以及如何给出图像的路径?
我已经在 My Document
文件夹中放置了一张图片并指定了该路径,但它给出了一条错误消息。
我有以下代码。
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Test extends JPanel {
BufferedImage image;
public Test(BufferedImage image) {
this.image = image;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw image centered.
int x = (getWidth() - image.getWidth())/2;
int y = (getHeight() - image.getHeight())/2;
g.drawImage(image, x, y, this);
}
public static void main(String[] args) throws IOException {
String path = "images.jpeg";
BufferedImage image = ImageIO.read(new File(path));
Test contentPane = new Test(image);
// You'll want to be sure this component is opaque
// since it is required for contentPanes. Some
// LAFs may use non-opaque components.
contentPane.setOpaque(true);
contentPane.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5,5,5,5);
gbc.weightx = 1.0;
gbc.weighty = 1.0;
// Add components.
for(int j = 0; j < 8; j++) {
gbc.gridwidth = ((j+1)%2 == 0) ? GridBagConstraints.REMAINDER
: GridBagConstraints.RELATIVE;
contentPane.add(new JButton("button " + (j+1)), gbc);
}
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(contentPane);
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
} }
最佳答案
您的图片位置不多。
相对路径,在您的示例中,启动的应用程序在您启动它的文件夹中查找图像(请检查应用程序是否已启动)。您可以通过
"resources\\images.jpeg"
为图像和访问创建文件夹“资源”绝对路径,类似
"C:\\Documents and settings\\<username>\\My Documents\\images.jpeg"
类路径 - 将图像放在同一个文件夹/包中,您的测试类就在那里。该资源可以打包成.jar文件。
BufferedImage image = ImageIO.read(Test.class.getResourceAsStream("images.jpeg"));
任何有效的 URL,例如您的头像
BufferedImage image = ImageIO.read(URI.create("http://www.gravatar.com/avatar/d5f91983a9d9cfb69981b6108a63b412?s=32&d=identicon&r=PG").toURL());
关于java - 图片加载路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9001754/