Elj*_*jay 3 java swing image paintcomponent application-resource
我想在框架中添加图像但是我无法理解应该保留图像文件的位置以及如何给出图像的路径?
我已将图像放在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);
} }
Run Code Online (Sandbox Code Playgroud)
小智 9
您的图片几乎没有地方.
相对路径,在您的示例中,启动的应用程序在您启动它的文件夹中查找图像(请检查应用程序是否已启动).您可以为图像和访问创建文件夹"资源""resources\\images.jpeg"
绝对路径,类似于 "C:\\Documents and settings\\<username>\\My Documents\\images.jpeg"
classpath - 将图像放在相同的文件夹/包中,放置了Test类.此资源可以打包到.jar文件中.
BufferedImage image = ImageIO.read(Test.class.getResourceAsStream("images.jpeg"));
任何有效的网址,例如你的头像
BufferedImage image = ImageIO.read(URI.create("http://www.gravatar.com/avatar/d5f91983a9d9cfb69981b6108a63b412?s=32&d=identicon&r=PG").toURL());
我应该在哪里保留图像文件..
由于它看起来像一个"应用程序资源",我会说它放在应用程序的运行时类路径上.这通常可以通过images在Jar中添加(例如)到目录来实现.
..我应该如何给出图像的路径?
通过以下网址访问它:
URL urlToImage = this.getClass().getResource("/images/the.png");
Run Code Online (Sandbox Code Playgroud)
ImageIO.read()也可以接受URL甚至更多才多艺InputStream.
| 归档时间: |
|
| 查看次数: |
19157 次 |
| 最近记录: |