开发者

loading image in a JPanel

开发者 https://www.devze.com 2023-04-12 01:53 出处:网络
I have a JPanel (which I created using netbeans)and I need to load image in it, based on selection on previous page. Could anyone suggest how to do that. Also is JPanel the best way to do wh开发者_Sta

I have a JPanel (which I created using netbeans)and I need to load image in it, based on selection on previous page. Could anyone suggest how to do that. Also is JPanel the best way to do wh开发者_StackOverflow中文版at I am trying to do, or I could do something else ?

Efforts appreciated thanks!!


The easiest way to display an image is to use a JLabel and call its setIcon method (or its constructor). The icon can be loaded using one of the constructors of the ImageIcon class.

See http://download.oracle.com/javase/tutorial/uiswing/components/label.html for an example.


There are number of ways to read/load images in Java. Take a look at this tutorial.


This is a sample code demonstrating how to load image in JPanel; background.jpg is the image we are loading to the JPanel. Also note that this image should be available in the source.

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ImageTest {

    public static void main(String[] args) {
        ImagePanel panel = new ImagePanel(
            new ImageIcon("background.jpg").getImage());

        JFrame frame = new JFrame();
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}

class ImagePanel extends JPanel {

    private Image img;

    public ImagePanel(String img) {
        this(new ImageIcon(img).getImage());
    }

    public ImagePanel(Image img) {
        this.img = img;
        Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
        setPreferredSize(size);
        setMinimumSize(size);
        setMaximumSize(size);
        setSize(size);
        setLayout(null);
    }

    public void paintComponent(Graphics g) {
        g.drawImage(img, 0, 0, null);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消