mirko
mirko

Reputation: 13

Why is there no Picture in my Panel/Window?

whats wrong with my code? I just want to have a Picture in my Window...

//class ImagePanel:

public class ImagePanel extends JPanel {

    private static final long serialVersionUID = -7664761101121497912L;

    public Image i;

    public ImagePanel(Image i) {
        this.i = i;
    }

    @Override
    public void paintComponents(Graphics g) {
        super.paintComponent(g);        
        g.drawImage(this.i, 0, 0, null);
    }
}

//class Main

public class Main extends JFrame {

    public static void main(String[] args) {

    JFrame frame = new JFrame();
        frame.setSize(1024, 768);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        ImagePanel panel = null;

        try {
            panel = new ImagePanel(ImageIO.read(new File("D:/test.JPG")));
        } catch (IOException e) {
            e.printStackTrace();
        }

        frame.getContentPane().add(panel);
        frame.setVisible(true);
    }
}

There is just a Window without a picture :( Whats the problem? And is there an easy way to set size of the window == picture size?

Thank you!

Upvotes: 1

Views: 143

Answers (4)

Genzer
Genzer

Reputation: 2991

You must override paintComponent(Graphics g) instead of paintComponents(Graphics g).

Upvotes: 5

camickr
camickr

Reputation: 324147

The best solution is to use a JLabel. Don't reinvent wheel. There is no need for you to do custom painting.

But if you do custom painting then you need to override the getPreferredSize() method to be the size of the image so the layout manager can do their job.

Upvotes: 4

mKorbel
mKorbel

Reputation: 109823

please read this tutorials about Icon in Swing and your Image would by placed to the JLabel but with same way/funcioanlities as to the JPanel

Upvotes: 3

Richard Schneider
Richard Schneider

Reputation: 35477

I not at all familiar with Java panes, but don't you need to set the size of ImagePanel before you add it to the content pane.

Upvotes: 0

Related Questions