2uzhan.com
Advertisement
Now Place:2uzhan.com » Image for JFrame

Image for JFrame

Java Programming @ July 19, 2005   Views:0

Hi there.

I'd like to know how can I place an image in my JFrame?
Thanks.

--------------Solutions-------------

what conetxt of the picture did you mean -- background or picture with the reduced size at the defined bounds or something else?

I'd like to post the image as a background.
thanks...

Class with the accessibility to paint image as the background

Code:

import javax.swing.*;
import java.awt.*;

/**
 * User: denis Date: 21.07.2005 Time: 11:31:02
 */
public class ImagePanel extends JPanel {

    private Image backgroundImage;

    public ImagePanel(Image backgroundImage) {
        super();
        this.backgroundImage = backgroundImage;
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(this.backgroundImage, 0, 0, null);
    }
}

Example of using:

Code:

import javax.swing.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.io.File;
import java.io.IOException;

/**
 * User: denis Date: 13.07.2005 Time: 10:53:41
 */
public class A {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(1024, 768);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        /* Getting required image */
        Image backgroundImage = null;
        String pathToTheImage = /* Your path */ "C:\\test\\1.jpg";
        try {
            backgroundImage = ImageIO.read(new File(pathToTheImage));
        } catch (IOException e) {
            e.printStackTrace();
        }

        /* Initializing panel with the our image */
        ImagePanel panel = new ImagePanel(backgroundImage);

        frame.getContentPane().add(panel);
        frame.show();
    }
}

Thanks. I had my problem solved.

welcome )

Tags:
© 2018 2uzhan.com Contact