How do i load images in Jframe java(eclipse)

£可爱£侵袭症+ 提交于 2019-12-18 18:04:31

问题


I have an paneel.java file wich looks like the following code:

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.


回答1:


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);
    }
}



回答2:


you need to set a file path to the image..something like this

final ImageIcon icon = new ImageIcon("C:\\Users\\you\\Desktop\\test.gif");



回答3:


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 );
}



回答4:


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.



来源:https://stackoverflow.com/questions/18871150/how-do-i-load-images-in-jframe-javaeclipse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!