我如何在 Jframe java(eclipse) 中加载图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18871150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do i load images in Jframe java(eclipse)
提问by Rene
I have an paneel.java file wich looks like the following code:
我有一个 panel.java 文件,它看起来像下面的代码:
import java.awt.*;
import javax.swing.*;
public class Paneel extends JFrame
{
public static void main ( String [] args )
{
// frame
JFrame frame = new Paneel();
frame.setSize ( 1000, 1000 );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setTitle( "Remembory" );
frame.setVisible( true );
}
class Gifpaneel extends JPanel{
private ImageIcon gif, animatedGif;
public Gifpaneel() {
gif = new ImageIcon( "test.gif" );
animatedGif = new ImageIcon( "animaties/test.gif" );
}
public void paintComponent( Graphics g ){
super.paintComponent( g );
gif.paintIcon( this, g, 100, 100 );
animatedGif.paintIcon ( this, g, 250, 100 );
}
}
}
i would like to show the test.gif file. How do i get this done? because when i run it in eclipse i only get the jframe with no image in it.
我想显示 test.gif 文件。我如何完成这项工作?因为当我在 eclipse 中运行它时,我只能得到没有图像的 jframe。
采纳答案by Rakesh KR
Use this
用这个
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageInFrame {
public static void main(String[] args) throws IOException {
String path = "Image1.jpg";
File file = new File(path);
BufferedImage image = ImageIO.read(file);
JLabel label = new JLabel(new ImageIcon(image));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(label);
f.pack();
f.setLocation(200,200);
f.setVisible(true);
}
}
回答by TheKojuEffect
public static void main ( String [] args )
{
// frame
JFrame frame = new Paneel();
frame.setSize ( 1000, 1000 );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setTitle( "Remembory" );
// Add following
GifPaneel gifpan = new GifPaneel();
gifpan.repaint();
frame.add(gifpan);
frame.setVisible( true );
}
回答by javawocky
you need to set a file path to the image..something like this
你需要设置图像的文件路径..像这样
final ImageIcon icon = new ImageIcon("C:\Users\you\Desktop\test.gif");
回答by user3970177
create package named as images on your project file and import image in that perticular package. Now, take a lable and select the icon property and select image from class path.
在项目文件上创建名为图像的包,并在该特定包中导入图像。现在,拿一个标签并选择图标属性并从类路径中选择图像。