本帖最后由 chaozi2010 于 2010-04-20 18:27:56 编辑 How would you go about opening an image file called picture.jpg
A:Graphics.getGraphics("pricture.jpg");
B:Image img = Toolkit.getDefaultToolkit.getImage("pricture.jpg");
C:Graphics.openImage("pricture.jpg");
D:Image img = new Image("pricture.jpg");
------最佳解决方案--------------------------------------------------------
URL url= Thread.currentThread().getContextClassLoader().getResource("yourPackeage/pricture.jpg");
File file=new File(url.getFile());
yourPackage is a java package where your image is at
------其他解决方案--------------------------------------------------------
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setContentPane(new ImagePanel(new ImageIcon("test.gif").getImage()));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 100, 100);
frame.setVisible(true);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
frame.repaint();
}
}).start();
}
static class ImagePanel extends JPanel {
BufferedImage image;
public ImagePanel(Image image) {
// Not really need a BufferedImage, just a requirement
this.image = new BufferedImage(image.getWidth(null), image.getHeight(null),
BufferedImage.TYPE_4BYTE_ABGR);
Graphics g = this.image.getGraphics();
g.drawImage(image, 0, 0, null);
}
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null);
}
}
}
------其他解决方案--------------------------------------------------------
http://topic.csdn.net/u/20100415/19/60f5d705-73ff-4e57-ac59-80de3564af97